package com.vegetable.common.aspect;

import cn.hutool.core.util.NumberUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.vegetable.modules.entity.inbound.AgentDelivery;
import com.vegetable.modules.entity.inbound.AgentDeliveryDetail;
import com.vegetable.modules.entity.inbound.OrderCost;
import com.vegetable.modules.entity.inbound.PackDelivery;
import com.vegetable.modules.entity.inbound.PackDeliveryDetail;
import com.vegetable.modules.entity.inbound.PurchaseDelivery;
import com.vegetable.modules.entity.inbound.PurchaseDeliveryDetail;
import com.vegetable.modules.entity.outbound.SalesOrderDetail;
import com.vegetable.modules.entity.outbound.SalesOrderDetailStock;
import com.vegetable.modules.entity.stock.CostWeightChangeSource;
import com.vegetable.modules.entity.stock.Stock;
import com.vegetable.modules.entity.stock.dto.OrderCostChangeDTO;
import com.vegetable.modules.entity.sys.SysUserEntity;
import com.vegetable.modules.service.inbound.IAgentDeliveryDetailService;
import com.vegetable.modules.service.inbound.IAgentDeliveryService;
import com.vegetable.modules.service.inbound.IOrderCostService;
import com.vegetable.modules.service.inbound.IPackDeliveryService;
import com.vegetable.modules.service.inbound.IPurchaseDeliveryService;
import com.vegetable.modules.service.outbound.ISalesOrderDetailService;
import com.vegetable.modules.service.outbound.ISalesOrderDetailStockService;
import com.vegetable.modules.service.stock.IChainCostChangeService;
import com.vegetable.modules.service.stock.ICostWeightChangeSourceService;
import com.vegetable.modules.service.stock.IStockService;
import com.vegetable.common.annotation.CostAllocationOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * <p>
 * 成本单价变化切面
 * </p>
 *
 * @author wangruijie
 * @since 2024-03-21
 */
@Slf4j
@Aspect
@Component
@Order(1) // 设置切面优先级，数值越小优先级越高
public class CostWeightChangeAspect {
    
    @Resource
    private IStockService stockService;
    
    @Autowired
    private ICostWeightChangeSourceService costWeightChangeSourceService;
    
    @Autowired
    private IChainCostChangeService chainCostChangeService;
    
    @Autowired
    private IAgentDeliveryService agentDeliveryService;
    
    @Autowired
    private IAgentDeliveryDetailService agentDeliveryDetailService; // 添加订单详情服务
    
    @Autowired
    private IPurchaseDeliveryService purchaseDeliveryService;
    
    @Autowired
    private ISalesOrderDetailService salesOrderDetailService;
    
    @Autowired
    private ISalesOrderDetailStockService salesOrderDetailStockService;
    
    @Autowired
    private IPackDeliveryService packDeliveryService;
    
    @Autowired
    private IOrderCostService orderCostService; // 添加订单费用服务
    
    // 用于追踪连锁变化的线程局部变量
    private static final ThreadLocal<Map<Long, CostWeightChangeSource>> CHANGE_CHAIN_TRACKER = 
        ThreadLocal.withInitial(ConcurrentHashMap::new);
    
    // 用于追踪事务ID的线程局部变量
    public static final ThreadLocal<String> TRACE_TRANSACTION_ID = new ThreadLocal<>();
    
    // 新增：用于标识是否已初始化链路ID的线程局部变量
    private static final ThreadLocal<Boolean> TTID_INITIALIZED = ThreadLocal.withInitial(() -> Boolean.FALSE);
    
    // 新增：用于防止切面重复进入的线程局部变量
    private static final ThreadLocal<Boolean> IN_COST_WEIGHT_ASPECT = new ThreadLocal<>();
    
    // 新增：用于存储方法执行前的数据状态
    private static final ThreadLocal<DataSnapshot> BEFORE_EXECUTION_DATA = new ThreadLocal<>();
    
    // 新增：异步执行器
    private static final ExecutorService ASYNC_EXECUTOR = Executors.newFixedThreadPool(10);

    // 新增：数据快照类
    private static class DataSnapshot {
        Map<Long, List<Stock>> beforeStocks = new HashMap<>();
        Map<Long, List<OrderCost>> beforeOrderCosts = new HashMap<>();
    }

    /**
     * 定义切点：拦截业务入口方法
     * 只拦截业务入口方法，内部调用的方法不直接拦截
     */
    @Pointcut("execution(* com.vegetable.modules.service.inbound.impl.PurchaseDeliveryServiceImpl.savePurchaseDelivery(..)) || " +
              "execution(* com.vegetable.modules.service.inbound.impl.PurchaseDeliveryServiceImpl.submitPurchaseDelivery(..)) || " +
              "execution(* com.vegetable.modules.service.inbound.impl.AgentDeliveryServiceImpl.submitAgentDelivery(..)) || " +
              "execution(* com.vegetable.modules.service.inbound.impl.AgentDeliveryServiceImpl.currentAgentDelivery(..)) || " +
              "@annotation(com.vegetable.common.annotation.CostAllocationOperation)")
    public void businessEntryPointPointcut() {
    }

    /**
     * 环绕通知：记录CostWeight变化
     */
    @Around("businessEntryPointPointcut()")
    public Object aroundBusinessEntryPoint(ProceedingJoinPoint point) throws Throwable {
        log.info("进入CostWeight变化切面，方法: {}", point.getSignature().toShortString());
        
        // 检查是否已经在切面中，避免重复进入
        if (IN_COST_WEIGHT_ASPECT.get() != null && IN_COST_WEIGHT_ASPECT.get()) {
            log.debug("已在CostWeight切面中，跳过重复处理");
            return point.proceed();
        }
        
        // 确保在主线程中初始化ttid
        log.debug("开始在主线程中初始化ttid");
        getTraceTransactionId();
        String traceId = TRACE_TRANSACTION_ID.get();
        log.info("在主线程中初始化traceId完成: {}", traceId);
        
        try {
            // 标记已进入切面
            IN_COST_WEIGHT_ASPECT.set(true);
            
            // 在方法执行前异步查询数据
            log.debug("开始执行queryDataBeforeExecutionAsync");
            CompletableFuture<DataSnapshot> beforeDataFuture = queryDataBeforeExecutionAsync(point);
            log.debug("queryDataBeforeExecutionAsync执行完成");
            
            // 执行原方法，并传递beforeDataFuture给后续处理
            log.debug("开始执行原方法");
            Object result = point.proceed();
            log.debug("原方法执行完成");
            
            // 在方法执行后异步查询数据并对比
            log.debug("开始执行compareDataAsync");
            compareDataAsync(point, beforeDataFuture);
            log.debug("compareDataAsync执行完成");
            
            return result;
        } finally {
            // 清理标记和数据
            log.debug("开始清理ThreadLocal变量");
            cleanup();
            log.debug("ThreadLocal变量清理完成");
        }
    }
    
    /**
     * 在方法执行前异步查询数据
     */
    private CompletableFuture<DataSnapshot> queryDataBeforeExecutionAsync(ProceedingJoinPoint point) {
        // 在主线程中获取ttid并传递给异步任务
        String traceId = TRACE_TRANSACTION_ID.get();
        log.info("在主线程中获取到traceId用于传递给异步任务: {}", traceId);
        return CompletableFuture.supplyAsync(() -> {
            try {
                log.debug("进入异步任务supplyAsync");
                // 在异步线程中设置ttid
                if (traceId != null) {
                    TRACE_TRANSACTION_ID.set(traceId);
                    log.info("在异步线程中设置traceId成功: {}", traceId);
                } else {
                    log.warn("traceId为空，无法在异步线程中设置");
                }
                
                log.info("开始异步查询方法执行前的数据");
                DataSnapshot dataSnapshot = new DataSnapshot();
                
                // 根据方法类型和参数查询相关数据
                String methodName = point.getSignature().getName();
                Object[] args = point.getArgs();
                
                log.info("处理方法: {}, 参数数量: {}", methodName, args != null ? args.length : 0);
                
                if (("savePurchaseDelivery".equals(methodName) || "submitPurchaseDelivery".equals(methodName))) {
                    handlePurchaseDeliveryData(point, dataSnapshot, args);
                } else if (("submitAgentDelivery".equals(methodName) || "currentAgentDelivery".equals(methodName))) {
                    handleAgentDeliveryData(point, dataSnapshot, args);
                } else {
                    log.warn("未识别的方法类型: {}", methodName);
                }
                
                log.info("方法执行前数据查询完成，DataSnapshot已创建");
                return dataSnapshot;
            } catch (Exception e) {
                log.error("查询方法执行前数据时发生错误", e);
                return new DataSnapshot(); // 返回空的DataSnapshot以避免后续处理出错
            }
        }, ASYNC_EXECUTOR);
    }
    
    /**
     * 处理采购收货相关数据
     */
    private void handlePurchaseDeliveryData(ProceedingJoinPoint point, DataSnapshot dataSnapshot, Object[] args) {
        try {
            log.info("开始处理采购收货数据，参数数量: {}", args != null ? args.length : 0);
            boolean foundDelivery = false;
            for (Object arg : args) {
                if (arg instanceof PurchaseDelivery) {
                    foundDelivery = true;
                    PurchaseDelivery delivery = (PurchaseDelivery) arg;
                    log.info("找到PurchaseDelivery对象，ID: {}", delivery.getId());
                    if (delivery.getId() != null) {
                        // 查询库存信息
                        List<Stock> stocks = stockService.queryStockByOrderId(delivery.getId());
                        dataSnapshot.beforeStocks.put(delivery.getId(), stocks != null ? stocks : new ArrayList<>());
                        
                        // 查询订单费用信息
                        List<OrderCost> orderCosts = orderCostService.selectByMainId(delivery.getId());
                        dataSnapshot.beforeOrderCosts.put(delivery.getId(), orderCosts != null ? orderCosts : new ArrayList<>());
                        
                        log.info("采购收货数据查询完成，订单ID: {}, 库存记录数: {}, 订单费用记录数: {}", 
                            delivery.getId(), 
                            stocks != null ? stocks.size() : 0, 
                            orderCosts != null ? orderCosts.size() : 0);
                    } else {
                        log.warn("PurchaseDelivery对象ID为空");
                    }
                    break;
                }
            }
            if (!foundDelivery) {
                log.warn("未找到PurchaseDelivery对象");
            }
        } catch (Exception e) {
            log.error("处理采购收货数据时发生错误", e);
        }
    }
    
    /**
     * 处理代办交货相关数据
     */
    private void handleAgentDeliveryData(ProceedingJoinPoint point, DataSnapshot dataSnapshot, Object[] args) {
        try {
            log.info("开始处理代办交货数据，参数数量: {}", args != null ? args.length : 0);
            boolean foundDelivery = false;
            for (Object arg : args) {
                if (arg instanceof AgentDelivery) {
                    foundDelivery = true;
                    AgentDelivery delivery = (AgentDelivery) arg;
                    log.info("找到AgentDelivery对象，ID: {}", delivery.getId());
                    if (delivery.getId() != null) {
                        // 查询库存信息
                        List<Stock> stocks = stockService.queryStockByOrderId(delivery.getId());
                        dataSnapshot.beforeStocks.put(delivery.getId(), stocks != null ? stocks : new ArrayList<>());
                        
                        // 查询订单费用信息
                        List<OrderCost> orderCosts = orderCostService.selectByMainId(delivery.getId());
                        dataSnapshot.beforeOrderCosts.put(delivery.getId(), orderCosts != null ? orderCosts : new ArrayList<>());
                        
                        log.info("代办交货数据查询完成，订单ID: {}, 库存记录数: {}, 订单费用记录数: {}", 
                            delivery.getId(), 
                            stocks != null ? stocks.size() : 0, 
                            orderCosts != null ? orderCosts.size() : 0);
                    } else {
                        log.warn("AgentDelivery对象ID为空");
                    }
                    break;
                }
            }
            if (!foundDelivery) {
                log.warn("未找到AgentDelivery对象");
            }
        } catch (Exception e) {
            log.error("处理代办交货数据时发生错误", e);
        }
    }
    
    /**
     * 在方法执行后异步查询数据并对比
     */
    private void compareDataAsync(ProceedingJoinPoint point, CompletableFuture<DataSnapshot> beforeDataFuture) {
        // 在主线程中获取ttid并传递给异步任务
        String traceId = TRACE_TRANSACTION_ID.get();
        log.info("在主线程中获取到traceId用于传递给异步任务: {}", traceId);
        CompletableFuture.runAsync(() -> {
            try {
                log.debug("进入异步任务runAsync");
                // 在异步线程中设置ttid
                if (traceId != null) {
                    TRACE_TRANSACTION_ID.set(traceId);
                    log.info("在异步线程中设置traceId成功: {}", traceId);
                } else {
                    log.warn("traceId为空，无法在异步线程中设置");
                }
                
                log.info("开始异步查询方法执行后的数据并进行对比");
                DataSnapshot beforeDataSnapshot = beforeDataFuture.get(); // 从CompletableFuture中获取数据
                if (beforeDataSnapshot == null) {
                    log.warn("未找到方法执行前的数据");
                    return;
                }
                
                // 根据方法类型查询相关数据并对比
                String methodName = point.getSignature().getName();
                Object[] args = point.getArgs();
                
                log.info("处理方法: {}, 参数数量: {}", methodName, args != null ? args.length : 0);
                
                // 检查是否是成本分摊操作
                if (isCostAllocationOperation(point)) {
                    compareCostAllocationData(point, args);
                } else if (("savePurchaseDelivery".equals(methodName) || "submitPurchaseDelivery".equals(methodName))) {
                    comparePurchaseDeliveryData(point, beforeDataSnapshot, args);
                } else if (("submitAgentDelivery".equals(methodName) || "currentAgentDelivery".equals(methodName))) {
                    compareAgentDeliveryData(point, beforeDataSnapshot, args);
                } else {
                    log.warn("未识别的方法类型: {}", methodName);
                }
                
                log.info("方法执行后数据查询和对比完成");
            } catch (Exception e) {
                log.error("查询方法执行后数据或对比时发生错误", e);
            } finally {
                // 清理异步线程中的ThreadLocal变量
                log.debug("开始清理异步线程中的ThreadLocal变量");
                cleanupThreadLocals();
                log.debug("异步线程中的ThreadLocal变量清理完成");
            }
        }, ASYNC_EXECUTOR);
    }
    
    /**
     * 检查是否是成本分摊操作
     */
    private boolean isCostAllocationOperation(ProceedingJoinPoint point) {
        try {
            // 检查方法上是否有CostAllocationOperation注解
            CostAllocationOperation annotation = point.getTarget().getClass()
                .getMethod(point.getSignature().getName(), 
                          ((org.aspectj.lang.reflect.MethodSignature) point.getSignature()).getParameterTypes())
                .getAnnotation(CostAllocationOperation.class);
            return annotation != null;
        } catch (NoSuchMethodException e) {
            log.error("检查方法是否是成本分摊操作时发生错误", e);
            return false;
        } catch (Exception e) {
            log.debug("无法获取方法注解信息: {}", e.getMessage());
            return false;
        }
    }
    
    /**
     * 对比成本分摊数据
     */
    private void compareCostAllocationData(ProceedingJoinPoint point, Object[] args) {
        try {
            log.info("开始对比成本分摊数据");
            
            // 对于成本分摊操作，我们不需要复杂的前后数据对比
            // 直接记录成本变化即可
            handleCostAllocationOperation(point, args);
            
            log.info("成本分摊数据对比完成");
        } catch (Exception e) {
            log.error("对比成本分摊数据时发生错误", e);
        }
    }
    
    /**
     * 处理成本分摊操作
     */
    private void handleCostAllocationOperation(ProceedingJoinPoint point, Object[] args) {
        try {
            log.info("处理成本分摊操作");
            
            // 这里可以添加特定的成本分摊操作处理逻辑
            // 例如记录特殊的成本分摊事件等
            
            log.info("成本分摊操作处理完成");
        } catch (Exception e) {
            log.error("处理成本分摊操作时发生错误", e);
        }
    }
    
    /**
     * 对比采购收货数据
     */
    private void comparePurchaseDeliveryData(ProceedingJoinPoint point, DataSnapshot beforeDataSnapshot, Object[] args) {
        try {
            Long orderId = null;
            for (Object arg : args) {
                if (arg instanceof PurchaseDelivery) {
                    PurchaseDelivery delivery = (PurchaseDelivery) arg;
                    orderId = delivery.getId();
                    break;
                }
            }
            
            if (orderId != null) {
                // 查询执行后的库存信息
                List<Stock> afterStocks = stockService.queryStockByOrderId(orderId);
                // 查询执行后的订单费用信息
                List<OrderCost> afterOrderCosts = orderCostService.selectByMainId(orderId);
                
                // 获取执行前的数据
                List<Stock> beforeStocks = beforeDataSnapshot.beforeStocks.get(orderId);
                List<OrderCost> beforeOrderCosts = beforeDataSnapshot.beforeOrderCosts.get(orderId);
                
                // 对比数据变化
                compareDataChanges(
                    beforeStocks != null ? beforeStocks : new ArrayList<>(),
                    afterStocks != null ? afterStocks : new ArrayList<>(),
                    beforeOrderCosts != null ? beforeOrderCosts : new ArrayList<>(),
                    afterOrderCosts != null ? afterOrderCosts : new ArrayList<>(),
                    point
                );
            }
        } catch (Exception e) {
            log.error("对比采购收货数据时发生错误", e);
        }
    }
    
    /**
     * 对比代办交货数据
     */
    private void compareAgentDeliveryData(ProceedingJoinPoint point, DataSnapshot beforeDataSnapshot, Object[] args) {
        try {
            Long orderId = null;
            for (Object arg : args) {
                if (arg instanceof AgentDelivery) {
                    AgentDelivery delivery = (AgentDelivery) arg;
                    orderId = delivery.getId();
                    break;
                }
            }
            
            if (orderId != null) {
                // 查询执行后的库存信息
                List<Stock> afterStocks = stockService.queryStockByOrderId(orderId);
                // 查询执行后的订单费用信息
                List<OrderCost> afterOrderCosts = orderCostService.selectByMainId(orderId);
                
                // 获取执行前的数据
                List<Stock> beforeStocks = beforeDataSnapshot.beforeStocks.get(orderId);
                List<OrderCost> beforeOrderCosts = beforeDataSnapshot.beforeOrderCosts.get(orderId);
                
                // 对比数据变化
                compareDataChanges(
                    beforeStocks != null ? beforeStocks : new ArrayList<>(),
                    afterStocks != null ? afterStocks : new ArrayList<>(),
                    beforeOrderCosts != null ? beforeOrderCosts : new ArrayList<>(),
                    afterOrderCosts != null ? afterOrderCosts : new ArrayList<>(),
                    point
                );
            }
        } catch (Exception e) {
            log.error("对比代办交货数据时发生错误", e);
        }
    }

    /**
     * 对比数据变化
     */
    /**
     * 对比数据变化
     */
    private void compareDataChanges(List<Stock> beforeStocks, List<Stock> afterStocks,
                                    List<OrderCost> beforeOrderCosts, List<OrderCost> afterOrderCosts,
                                    ProceedingJoinPoint point) {
        try {
            log.info("开始对比数据变化");
            log.debug("对比数据变化 - 前置库存数据数量: {}, 后置库存数据数量: {}",
                    beforeStocks != null ? beforeStocks.size() : "null",
                    afterStocks != null ? afterStocks.size() : "null");
            log.debug("对比数据变化 - 前置订单费用数据数量: {}, 后置订单费用数据数量: {}",
                    beforeOrderCosts != null ? beforeOrderCosts.size() : "null",
                    afterOrderCosts != null ? afterOrderCosts.size() : "null");

            // 创建统一的变更记录实体
            List<CostWeightChangeSource> changeRecords = new ArrayList<>();

            // 记录订单费用的详细变化情况
            logOrderCostChanges(beforeOrderCosts, afterOrderCosts);

            // 对比库存变化并收集变更记录
            compareStockChanges(beforeStocks, afterStocks, point, changeRecords);

            // 对比订单费用变化并收集变更记录
            compareOrderCostChanges(beforeOrderCosts, afterOrderCosts, point, changeRecords);

            // 合并同一链路ID下的所有变更记录为一条记录
            List<CostWeightChangeSource> mergedRecords = mergeChangeRecordsByTtid(changeRecords);

            // 保存合并后的变更记录
            if (!mergedRecords.isEmpty()) {
                for (CostWeightChangeSource changeRecord : mergedRecords) {
                    // 确保链路ID已设置
                    if (changeRecord.getTtid() == null) {
                        String traceId = TRACE_TRANSACTION_ID.get();
                        if (traceId != null) {
                            changeRecord.setTtid(traceId);
                        }
                    }
                    costWeightChangeSourceService.saveOrUpdate(changeRecord);
                }
                log.info("已保存 {} 条合并后的变更记录", mergedRecords.size());
            }

            log.info("数据变化对比完成");
        } catch (Exception e) {
            log.error("对比数据变化时发生错误", e);
        }
    }

    /**
     * 根据链路ID合并变更记录
     * @param changeRecords 变更记录列表
     * @return 合并后的变更记录列表
     */
    private List<CostWeightChangeSource> mergeChangeRecordsByTtid(List<CostWeightChangeSource> changeRecords) {
        try {
            if (changeRecords == null || changeRecords.isEmpty()) {
                return new ArrayList<>();
            }

            // 按链路ID分组
            Map<String, List<CostWeightChangeSource>> groupedByTtid = new HashMap<>();
            for (CostWeightChangeSource record : changeRecords) {
                String ttid = record.getTtid();
                groupedByTtid.computeIfAbsent(ttid, k -> new ArrayList<>()).add(record);
            }

            // 合并每组记录
            List<CostWeightChangeSource> mergedRecords = new ArrayList<>();
            for (Map.Entry<String, List<CostWeightChangeSource>> entry : groupedByTtid.entrySet()) {
                List<CostWeightChangeSource> groupRecords = entry.getValue();
                if (!groupRecords.isEmpty()) {
                    // 同一条链路上的再根据商品信息分组
                    Map<String, List<CostWeightChangeSource>> groupedByCommodity = new HashMap<>();
                    for (CostWeightChangeSource record : groupRecords) {
                        String mark = record.getCommodityId() + record.getSpecsId() + "";
                        groupedByCommodity.computeIfAbsent(mark, k -> new ArrayList<>()).add(record);
                    }
                    for (Map.Entry<String, List<CostWeightChangeSource>> en : groupedByCommodity.entrySet()) {
                        // 合并为一条记录
                        CostWeightChangeSource mergedRecord = mergeRecords(en.getValue());
                        mergedRecords.add(mergedRecord);
                    }
                }
            }

            log.info("合并变更记录完成，原始记录数: {}, 合并后记录数: {}", changeRecords.size(), mergedRecords.size());
            return mergedRecords;
        } catch (Exception e) {
            log.error("合并变更记录时发生错误", e);
            return changeRecords; // 出错时返回原始记录
        }
    }

    /**
     * 合并多条记录为一条记录
     * @param records 要合并的记录列表
     * @return 合并后的记录
     */
    private CostWeightChangeSource mergeRecords(List<CostWeightChangeSource> records) {
        if (records == null || records.isEmpty()) {
            return null;
        }

        // 使用第一条记录作为基础
        CostWeightChangeSource mergedRecord = new CostWeightChangeSource();
        CostWeightChangeSource firstRecord = records.get(0);

        // 复制基础信息
        mergedRecord.setTtid(firstRecord.getTtid());
        mergedRecord.setStockId(firstRecord.getStockId());
        mergedRecord.setCommodityId(firstRecord.getCommodityId());
        mergedRecord.setCommodityName(firstRecord.getCommodityName());
        mergedRecord.setSpecsId(firstRecord.getSpecsId());
        mergedRecord.setSpecsName(firstRecord.getSpecsName());
        mergedRecord.setStockBatchNo(firstRecord.getStockBatchNo());
        mergedRecord.setSourceOrderId(firstRecord.getSourceOrderId());
        mergedRecord.setSourceOrderNo(firstRecord.getSourceOrderNo());
        mergedRecord.setSourceOrderType(firstRecord.getSourceOrderType());
        mergedRecord.setRelatedCommodityId(firstRecord.getRelatedCommodityId());
        mergedRecord.setRelatedCommodityName(firstRecord.getRelatedCommodityName());
        mergedRecord.setOperatorId(firstRecord.getOperatorId());
        mergedRecord.setOperatorName(firstRecord.getOperatorName());
        mergedRecord.setOperateTime(firstRecord.getOperateTime());

        // 合并变化信息
        StringBuilder remarkBuilder = new StringBuilder();
        StringBuilder detailInfoBuilder = new StringBuilder();
        remarkBuilder.append("合并变更记录: ");

        // 初始化变化值
        BigDecimal beforeCostWeight = null;
        BigDecimal afterCostWeight = null;
        BigDecimal beforeGoodsUnitPrice = null;
        BigDecimal afterGoodsUnitPrice = null;
        BigDecimal beforePackageUnitPrice = null;
        BigDecimal afterPackageUnitPrice = null;

        // 处理每条记录
        List<String> sourceTypes = new ArrayList<>();
        for (int i = 0; i < records.size(); i++) {
            CostWeightChangeSource record = records.get(i);

            // 收集变化类型
            if (record.getSourceType() != null && !sourceTypes.contains(record.getSourceType().toString())) {
                sourceTypes.add(record.getSourceType().toString());
            }

            // 设置初始和最终值
            if (i == 0) {
                beforeCostWeight = record.getBeforeCostWeight();
                beforeGoodsUnitPrice = record.getBeforeGoodsUnitPrice();
                beforePackageUnitPrice = record.getBeforePackageUnitPrice();
            }
            if (i == records.size() - 1) {
                afterCostWeight = record.getAfterCostWeight();
                afterGoodsUnitPrice = record.getAfterGoodsUnitPrice();
                afterPackageUnitPrice = record.getAfterPackageUnitPrice();
            }

            // 添加备注信息
            if (record.getRemark() != null && !record.getRemark().isEmpty()) {
                if (remarkBuilder.length() > 0) {
                    remarkBuilder.append("; ");
                }
                remarkBuilder.append(record.getRemark());
            }

            // 添加详细信息
            if (record.getDetailInfo() != null && !record.getDetailInfo().isEmpty()) {
                if (detailInfoBuilder.length() > 0) {
                    detailInfoBuilder.append("\n");
                }
                detailInfoBuilder.append(record.getDetailInfo());
            }

            // 处理订单费用变化信息
            if (record.getOrderCostChanges() != null && !record.getOrderCostChanges().isEmpty()) {
                if (detailInfoBuilder.length() > 0) {
                    detailInfoBuilder.append("\n");
                }
                detailInfoBuilder.append("订单费用变化: ").append(record.getOrderCostChanges());
            }
        }

        // 设置合并后的值
        mergedRecord.setBeforeCostWeight(beforeCostWeight);
        mergedRecord.setAfterCostWeight(afterCostWeight);
        mergedRecord.setChangeAmount(NumberUtil.sub(afterCostWeight, beforeCostWeight));
        mergedRecord.setBeforeGoodsUnitPrice(beforeGoodsUnitPrice);
        mergedRecord.setAfterGoodsUnitPrice(afterGoodsUnitPrice);
        mergedRecord.setGoodsUnitPriceChangeAmount(NumberUtil.sub(afterGoodsUnitPrice, beforeGoodsUnitPrice));
        mergedRecord.setBeforePackageUnitPrice(beforePackageUnitPrice);
        mergedRecord.setAfterPackageUnitPrice(afterPackageUnitPrice);
        mergedRecord.setPackageUnitPriceChangeAmount(NumberUtil.sub(afterPackageUnitPrice, beforePackageUnitPrice));

        // 设置变化类型（如果只有一种类型则使用该类型，否则使用合并类型）
        if (sourceTypes.size() == 1) {
            try {
                mergedRecord.setSourceType(Integer.parseInt(sourceTypes.get(0)));
            } catch (NumberFormatException e) {
                mergedRecord.setSourceType(1); // 默认订单价格修改
            }
        } else {
            mergedRecord.setSourceType(1); // 合并类型使用订单价格修改
        }

        mergedRecord.setRemark(remarkBuilder.toString());
        mergedRecord.setDetailInfo(detailInfoBuilder.toString());

        log.debug("合并记录完成，合并了 {} 条记录", records.size());
        return mergedRecord;
    }


    /**
     * 记录订单费用的详细变化情况
     */
    private void logOrderCostChanges(List<OrderCost> beforeOrderCosts, List<OrderCost> afterOrderCosts) {
        try {
            log.info("开始记录订单费用变化详情");
            
            // 修改逻辑：即使其中一个为空，也要处理新增或删除的情况
            if (beforeOrderCosts == null && afterOrderCosts == null) {
                log.info("订单费用数据都为空，无变化需要记录");
                return;
            }
            
            // 如果beforeOrderCosts为null，创建空列表
            if (beforeOrderCosts == null) {
                log.info("前置订单费用数据为空，创建空列表");
                beforeOrderCosts = new ArrayList<>();
            }
            
            // 如果afterOrderCosts为null，创建空列表
            if (afterOrderCosts == null) {
                log.info("后置订单费用数据为空，创建空列表");
                afterOrderCosts = new ArrayList<>();
            }
            
            // 创建费用条款ID到费用对象的映射
            Map<Long, OrderCost> beforeOrderCostMap = new HashMap<>();
            Map<Long, OrderCost> afterOrderCostMap = new HashMap<>();
            
            // 填充前置费用映射
            for (OrderCost orderCost : beforeOrderCosts) {
                if (orderCost.getCostClauseId() != null) {
                    beforeOrderCostMap.put(orderCost.getCostClauseId(), orderCost);
                }
            }
            
            // 填充后置费用映射
            for (OrderCost orderCost : afterOrderCosts) {
                if (orderCost.getCostClauseId() != null) {
                    afterOrderCostMap.put(orderCost.getCostClauseId(), orderCost);
                }
            }
            
            // 记录新增的费用
            for (Long costClauseId : afterOrderCostMap.keySet()) {
                if (!beforeOrderCostMap.containsKey(costClauseId)) {
                    OrderCost newOrderCost = afterOrderCostMap.get(costClauseId);
                    log.info("新增订单费用 - 费用条款ID: {}, 费用条款名称: {}, 变化金额: {}", 
                            costClauseId, 
                            newOrderCost.getCostClauseName() != null ? newOrderCost.getCostClauseName() : "未知", 
                            newOrderCost.getMoney() != null ? newOrderCost.getMoney() : BigDecimal.ZERO);
                }
            }
            
            // 记录删除的费用
            for (Long costClauseId : beforeOrderCostMap.keySet()) {
                if (!afterOrderCostMap.containsKey(costClauseId)) {
                    OrderCost deletedOrderCost = beforeOrderCostMap.get(costClauseId);
                    log.info("删除订单费用 - 费用条款ID: {}, 费用条款名称: {}, 变化金额: {}", 
                            costClauseId, 
                            deletedOrderCost.getCostClauseName() != null ? deletedOrderCost.getCostClauseName() : "未知", 
                            deletedOrderCost.getMoney() != null ? deletedOrderCost.getMoney().negate() : BigDecimal.ZERO);
                }
            }
            
            // 记录修改的费用
            for (Long costClauseId : beforeOrderCostMap.keySet()) {
                if (afterOrderCostMap.containsKey(costClauseId)) {
                    OrderCost beforeOrderCost = beforeOrderCostMap.get(costClauseId);
                    OrderCost afterOrderCost = afterOrderCostMap.get(costClauseId);
                    
                    // 检查金额是否发生变化
                    if (hasMoneyChanged(beforeOrderCost, afterOrderCost)) {
                        BigDecimal changeAmount = afterOrderCost.getMoney().subtract(beforeOrderCost.getMoney());
                        log.info("修改订单费用 - 费用条款ID: {}, 费用条款名称: {}, 变化前金额: {}, 变化后金额: {}, 变化金额: {}", 
                                costClauseId, 
                                beforeOrderCost.getCostClauseName() != null ? beforeOrderCost.getCostClauseName() : "未知",
                                beforeOrderCost.getMoney() != null ? beforeOrderCost.getMoney() : BigDecimal.ZERO,
                                afterOrderCost.getMoney() != null ? afterOrderCost.getMoney() : BigDecimal.ZERO,
                                changeAmount);
                    }
                }
            }
            
            log.info("订单费用变化详情记录完成");
        } catch (Exception e) {
            log.error("记录订单费用变化详情时发生错误", e);
        }
    }

    /**
     * 对比库存变化
     */
    private void compareStockChanges(List<Stock> beforeStocks, List<Stock> afterStocks,
                                     ProceedingJoinPoint point, List<CostWeightChangeSource> changeRecords) {
        try {
            log.info("开始对比库存变化");
            log.debug("对比库存变化 - 前置库存数据: {}, 后置库存数据: {}",
                    beforeStocks != null ? beforeStocks.size() : "null",
                    afterStocks != null ? afterStocks.size() : "null");

            // 修改逻辑：即使其中一个为空，也要处理新增或删除的情况
            if (beforeStocks == null && afterStocks == null) {
                log.warn("库存数据都为空，无法对比");
                return;
            }

            // 如果beforeStocks为null，创建空列表
            if (beforeStocks == null) {
                log.info("前置库存数据为空，创建空列表");
                beforeStocks = new ArrayList<>();
            }

            // 如果afterStocks为null，创建空列表
            if (afterStocks == null) {
                log.info("后置库存数据为空，创建空列表");
                afterStocks = new ArrayList<>();
            }

            // 创建库存ID到库存对象的映射
            Map<Long, Stock> beforeStockMap = new HashMap<>();
            Map<Long, Stock> afterStockMap = new HashMap<>();

            for (Stock stock : beforeStocks) {
                if (stock.getId() != null) {
                    beforeStockMap.put(stock.getId(), stock);
                }
            }

            for (Stock stock : afterStocks) {
                if (stock.getId() != null) {
                    afterStockMap.put(stock.getId(), stock);
                }
            }

            log.debug("构建库存映射完成 - 前置库存映射数量: {}, 后置库存映射数量: {}",
                    beforeStockMap.size(), afterStockMap.size());

            // 检查新增的库存记录
            for (Long stockId : afterStockMap.keySet()) {
                if (!beforeStockMap.containsKey(stockId)) {
                    Stock newStock = afterStockMap.get(stockId);
                    log.info("发现新增库存记录，库存ID: {}, 商品名称: {}, 成本单价: {}",
                            stockId,
                            newStock.getCommodityName() != null ? newStock.getCommodityName() : "未知",
                            newStock.getCostWeight() != null ? newStock.getCostWeight() : BigDecimal.ZERO);
                    log.debug("新增库存详情: {}", newStock);
                    // 处理新增库存
                    handleNewStock(newStock, point, changeRecords);
                }
            }

            // 检查删除的库存记录
            for (Long stockId : beforeStockMap.keySet()) {
                if (!afterStockMap.containsKey(stockId)) {
                    Stock deletedStock = beforeStockMap.get(stockId);
                    log.info("发现删除库存记录，库存ID: {}, 商品名称: {}, 成本单价: {}",
                            stockId,
                            deletedStock.getCommodityName() != null ? deletedStock.getCommodityName() : "未知",
                            deletedStock.getCostWeight() != null ? deletedStock.getCostWeight() : BigDecimal.ZERO);
                    log.debug("删除库存详情: {}", deletedStock);
                    // 处理删除库存
                    handleDeletedStock(deletedStock, point, changeRecords);
                }
            }

            // 检查修改的库存记录
            for (Long stockId : beforeStockMap.keySet()) {
                if (afterStockMap.containsKey(stockId)) {
                    Stock beforeStock = beforeStockMap.get(stockId);
                    Stock afterStock = afterStockMap.get(stockId);

                    // 检查CostWeight是否发生变化
                    boolean costWeightChanged = hasCostWeightChanged(beforeStock, afterStock);
                    // 检查GoodsUnitPrice是否发生变化
                    boolean goodsUnitPriceChanged = hasGoodsUnitPriceChanged(beforeStock, afterStock);
                    // 检查PackageUnitPrice是否发生变化
                    boolean packageUnitPriceChanged = hasPackageUnitPriceChanged(beforeStock, afterStock);

                    // 如果任何一个字段发生变化，都需要记录
                    if (costWeightChanged || goodsUnitPriceChanged || packageUnitPriceChanged) {
                        BigDecimal changeAmount = BigDecimal.ZERO;
                        if (costWeightChanged) {
                            changeAmount = afterStock.getCostWeight().subtract(beforeStock.getCostWeight());
                            log.info("库存CostWeight发生变化，库存ID: {}, 商品名称: {}, 变化前成本单价: {}, 变化后成本单价: {}, 变化金额: {}",
                                    stockId,
                                    beforeStock.getCommodityName() != null ? beforeStock.getCommodityName() : "未知",
                                    beforeStock.getCostWeight() != null ? beforeStock.getCostWeight() : BigDecimal.ZERO,
                                    afterStock.getCostWeight() != null ? afterStock.getCostWeight() : BigDecimal.ZERO,
                                    changeAmount);
                            log.debug("库存CostWeight变化详情 - 变化前: {}, 变化后: {}",
                                    beforeStock.getCostWeight(), afterStock.getCostWeight());
                        }

                        // 记录GoodsUnitPrice变化
                        if (goodsUnitPriceChanged) {
                            BigDecimal goodsUnitPriceChange = (afterStock.getGoodsUnitPrice() != null ? afterStock.getGoodsUnitPrice() : BigDecimal.ZERO)
                                    .subtract(beforeStock.getGoodsUnitPrice() != null ? beforeStock.getGoodsUnitPrice() : BigDecimal.ZERO);
                            log.info("库存GoodsUnitPrice发生变化，库存ID: {}, 商品名称: {}, 变化前蔬菜单价: {}, 变化后蔬菜单价: {}, 变化金额: {}",
                                    stockId,
                                    beforeStock.getCommodityName() != null ? beforeStock.getCommodityName() : "未知",
                                    beforeStock.getGoodsUnitPrice() != null ? beforeStock.getGoodsUnitPrice() : BigDecimal.ZERO,
                                    afterStock.getGoodsUnitPrice() != null ? afterStock.getGoodsUnitPrice() : BigDecimal.ZERO,
                                    goodsUnitPriceChange);
                            log.debug("库存GoodsUnitPrice变化详情 - 变化前: {}, 变化后: {}",
                                    beforeStock.getGoodsUnitPrice(), afterStock.getGoodsUnitPrice());
                        }

                        // 记录PackageUnitPrice变化
                        if (packageUnitPriceChanged) {
                            BigDecimal packageUnitPriceChange = (afterStock.getPackageUnitPrice() != null ? afterStock.getPackageUnitPrice() : BigDecimal.ZERO)
                                    .subtract(beforeStock.getPackageUnitPrice() != null ? beforeStock.getPackageUnitPrice() : BigDecimal.ZERO);
                            log.info("库存PackageUnitPrice发生变化，库存ID: {}, 商品名称: {}, 变化前包装单价: {}, 变化后包装单价: {}, 变化金额: {}",
                                    stockId,
                                    beforeStock.getCommodityName() != null ? beforeStock.getCommodityName() : "未知",
                                    beforeStock.getPackageUnitPrice() != null ? beforeStock.getPackageUnitPrice() : BigDecimal.ZERO,
                                    afterStock.getPackageUnitPrice() != null ? afterStock.getPackageUnitPrice() : BigDecimal.ZERO,
                                    packageUnitPriceChange);
                            log.debug("库存PackageUnitPrice变化详情 - 变化前: {}, 变化后: {}",
                                    beforeStock.getPackageUnitPrice(), afterStock.getPackageUnitPrice());
                        }

                        // 处理库存变化
                        handleStockChange(beforeStock, afterStock, point, changeRecords);
                    } else {
                        log.debug("库存字段未发生变化，库存ID: {}", stockId);
                    }
                }
            }

            log.info("库存变化对比完成");
        } catch (Exception e) {
            log.error("对比库存变化时发生错误", e);
        }
    }

    /**
     * 对比订单费用变化
     */
    private void compareOrderCostChanges(List<OrderCost> beforeOrderCosts, List<OrderCost> afterOrderCosts,
                                         ProceedingJoinPoint point, List<CostWeightChangeSource> changeRecords) {
        try {
            log.info("开始对比订单费用变化");
            log.debug("对比订单费用变化 - 前置订单费用数据数量: {}, 后置订单费用数据数量: {}",
                    beforeOrderCosts != null ? beforeOrderCosts.size() : "null",
                    afterOrderCosts != null ? afterOrderCosts.size() : "null");

            // 修改逻辑：即使其中一个为空，也要处理新增或删除的情况
            if (beforeOrderCosts == null && afterOrderCosts == null) {
                log.warn("订单费用数据都为空，无法对比");
                return;
            }

            // 如果beforeOrderCosts为null，创建空列表
            if (beforeOrderCosts == null) {
                log.info("前置订单费用数据为空，创建空列表");
                beforeOrderCosts = new ArrayList<>();
            }

            // 如果afterOrderCosts为null，创建空列表
            if (afterOrderCosts == null) {
                log.info("后置订单费用数据为空，创建空列表");
                afterOrderCosts = new ArrayList<>();
            }

            // 创建费用条款ID到订单费用对象的映射
            Map<Long, OrderCost> beforeOrderCostMap = new HashMap<>();
            Map<Long, OrderCost> afterOrderCostMap = new HashMap<>();

            for (OrderCost orderCost : beforeOrderCosts) {
                if (orderCost.getCostClauseId() != null) {
                    beforeOrderCostMap.put(orderCost.getCostClauseId(), orderCost);
                }
            }

            for (OrderCost orderCost : afterOrderCosts) {
                if (orderCost.getCostClauseId() != null) {
                    afterOrderCostMap.put(orderCost.getCostClauseId(), orderCost);
                }
            }

            log.debug("构建订单费用映射完成 - 前置订单费用映射数量: {}, 后置订单费用映射数量: {}",
                    beforeOrderCostMap.size(), afterOrderCostMap.size());

            // 检查新增的订单费用记录
            for (Long costClauseId : afterOrderCostMap.keySet()) {
                if (!beforeOrderCostMap.containsKey(costClauseId)) {
                    OrderCost newOrderCost = afterOrderCostMap.get(costClauseId);
                    log.info("发现新增订单费用记录，费用条款ID: {}, 费用条款名称: {}, 金额: {}",
                            costClauseId,
                            newOrderCost.getCostClauseName() != null ? newOrderCost.getCostClauseName() : "未知",
                            newOrderCost.getMoney() != null ? newOrderCost.getMoney() : BigDecimal.ZERO);
                    log.debug("新增订单费用详情: {}", newOrderCost);
                    // 处理新增订单费用
                    handleNewOrderCost(newOrderCost, point, changeRecords);
                }
            }

            // 检查删除的订单费用记录
            for (Long costClauseId : beforeOrderCostMap.keySet()) {
                if (!afterOrderCostMap.containsKey(costClauseId)) {
                    OrderCost deletedOrderCost = beforeOrderCostMap.get(costClauseId);
                    log.info("发现删除订单费用记录，费用条款ID: {}, 费用条款名称: {}, 金额: {}",
                            costClauseId,
                            deletedOrderCost.getCostClauseName() != null ? deletedOrderCost.getCostClauseName() : "未知",
                            deletedOrderCost.getMoney() != null ? deletedOrderCost.getMoney() : BigDecimal.ZERO);
                    log.debug("删除订单费用详情: {}", deletedOrderCost);
                    // 处理删除订单费用
                    handleDeletedOrderCost(deletedOrderCost, point, changeRecords);
                }
            }

            // 检查修改的订单费用记录
            for (Long costClauseId : beforeOrderCostMap.keySet()) {
                if (afterOrderCostMap.containsKey(costClauseId)) {
                    OrderCost beforeOrderCost = beforeOrderCostMap.get(costClauseId);
                    OrderCost afterOrderCost = afterOrderCostMap.get(costClauseId);

                    // 检查金额是否发生变化
                    if (hasMoneyChanged(beforeOrderCost, afterOrderCost)) {
                        BigDecimal changeAmount = afterOrderCost.getMoney().subtract(beforeOrderCost.getMoney());
                        log.info("订单费用金额发生变化，费用条款ID: {}, 费用条款名称: {}, 变化前金额: {}, 变化后金额: {}, 变化金额: {}",
                                costClauseId,
                                beforeOrderCost.getCostClauseName() != null ? beforeOrderCost.getCostClauseName() : "未知",
                                beforeOrderCost.getMoney() != null ? beforeOrderCost.getMoney() : BigDecimal.ZERO,
                                afterOrderCost.getMoney() != null ? afterOrderCost.getMoney() : BigDecimal.ZERO,
                                changeAmount);
                        log.debug("订单费用金额变化详情 - 变化前: {}, 变化后: {}",
                                beforeOrderCost.getMoney(), afterOrderCost.getMoney());
                        // 处理订单费用变化
                        handleOrderCostChange(beforeOrderCost, afterOrderCost, point, changeRecords);
                    }
                }
            }

            log.info("订单费用变化详情记录完成");
        } catch (Exception e) {
            log.error("记录订单费用变化详情时发生错误", e);
        }
    }

    /**
     * 处理新增库存
     */
    private void handleNewStock(Stock stock, ProceedingJoinPoint point, List<CostWeightChangeSource> changeRecords) {
        try {
            log.info("处理新增库存，库存ID: {}", stock.getId());
            log.debug("新增库存详情: {}", stock);

            // 创建CostWeightChangeSource对象
            CostWeightChangeSource source = new CostWeightChangeSource();
            source.setStockId(stock.getId());
            source.setCommodityId(stock.getCommodityId());
            source.setCommodityName(stock.getCommodityName());
            // 设置规格ID和规格名称
            source.setSpecsId(stock.getSpecsId());
            source.setSpecsName(stock.getSpecsName());
            // 设置库存批次编码
            source.setStockBatchNo(stock.getStockBatchNo());
            source.setBeforeCostWeight(stock.getCostWeight());
            source.setAfterCostWeight(stock.getCostWeight());
            source.setChangeAmount(BigDecimal.ZERO);

            // 记录蔬菜单价和包装单价（保持不变）
            source.setBeforeGoodsUnitPrice(stock.getGoodsUnitPrice());
            source.setAfterGoodsUnitPrice(stock.getGoodsUnitPrice());
            source.setGoodsUnitPriceChangeAmount(BigDecimal.ZERO);
            source.setBeforePackageUnitPrice(stock.getPackageUnitPrice());
            source.setAfterPackageUnitPrice(stock.getPackageUnitPrice());
            source.setPackageUnitPriceChangeAmount(BigDecimal.ZERO);

            source.setSourceType(2); // 入库调整
            source.setChangeAmount(stock.getCostWeight());
            source.setOperateTime(new Date());
            source.setOperatorId(getCurrentUserId());
            source.setSourceOrderId(stock.getOrderId());
            source.setSourceOrderType(stock.getStorageType());
            source.setRemark("新增库存");

            // 添加详细的ttid设置日志
            log.debug("开始设置ttid到CostWeightChangeSource对象");
            String traceId = TRACE_TRANSACTION_ID.get();
            log.debug("从TRACE_TRANSACTION_ID获取的traceId: {}", traceId);
            if (traceId != null) {
                source.setTtid(traceId);
                log.info("成功为新增库存设置ttid: {}", traceId);
            } else {
                // 确保链路ID已初始化
                log.warn("TRACE_TRANSACTION_ID为空，尝试初始化");
                getTraceTransactionId();
                traceId = TRACE_TRANSACTION_ID.get();
                log.debug("初始化后获取的traceId: {}", traceId);
                if (traceId != null) {
                    source.setTtid(traceId);
                    log.info("初始化后成功为新增库存设置ttid: {}", traceId);
                } else {
                    log.error("无法为新增库存设置ttid，TRACE_TRANSACTION_ID仍然为空");
                }
            }

            // 将记录添加到变更记录列表中
            changeRecords.add(source);
            log.info("新增库存处理完成，库存ID: {}", stock.getId());
        } catch (Exception e) {
            log.error("处理新增库存时发生错误", e);
        }
    }

    /**
     * 处理删除库存
     */
    private void handleDeletedStock(Stock stock, ProceedingJoinPoint point, List<CostWeightChangeSource> changeRecords) {
        try {
            log.info("处理删除库存，库存ID: {}", stock.getId());
            log.debug("删除库存详情: {}", stock);

            // 创建CostWeightChangeSource对象
            CostWeightChangeSource source = new CostWeightChangeSource();
            source.setStockId(stock.getId());
            source.setCommodityId(stock.getCommodityId());
            source.setCommodityName(stock.getCommodityName());
            // 设置规格ID和规格名称
            source.setSpecsId(stock.getSpecsId());
            source.setSpecsName(stock.getSpecsName());
            // 设置库存批次编码
            source.setStockBatchNo(stock.getStockBatchNo());
            source.setBeforeCostWeight(stock.getCostWeight());
            source.setAfterCostWeight(stock.getCostWeight());
            source.setChangeAmount(BigDecimal.ZERO);

            // 记录蔬菜单价和包装单价（保持不变）
            source.setBeforeGoodsUnitPrice(stock.getGoodsUnitPrice());
            source.setAfterGoodsUnitPrice(stock.getGoodsUnitPrice());
            source.setGoodsUnitPriceChangeAmount(BigDecimal.ZERO);
            source.setBeforePackageUnitPrice(stock.getPackageUnitPrice());
            source.setAfterPackageUnitPrice(stock.getPackageUnitPrice());
            source.setPackageUnitPriceChangeAmount(BigDecimal.ZERO);

            source.setSourceType(2); // 入库调整
            source.setChangeAmount(stock.getCostWeight().negate());
            source.setOperateTime(new Date());
            source.setOperatorId(getCurrentUserId());
            source.setSourceOrderId(stock.getOrderId());
            source.setSourceOrderType(stock.getStorageType());
            source.setRemark("删除库存");

            // 添加详细的ttid设置日志
            log.debug("开始设置ttid到CostWeightChangeSource对象");
            String traceId = TRACE_TRANSACTION_ID.get();
            log.debug("从TRACE_TRANSACTION_ID获取的traceId: {}", traceId);
            if (traceId != null) {
                source.setTtid(traceId);
                log.info("成功为删除库存设置ttid: {}", traceId);
            } else {
                // 确保链路ID已初始化
                log.warn("TRACE_TRANSACTION_ID为空，尝试初始化");
                getTraceTransactionId();
                traceId = TRACE_TRANSACTION_ID.get();
                log.debug("初始化后获取的traceId: {}", traceId);
                if (traceId != null) {
                    source.setTtid(traceId);
                    log.info("初始化后成功为删除库存设置ttid: {}", traceId);
                } else {
                    log.error("无法为删除库存设置ttid，TRACE_TRANSACTION_ID仍然为空");
                }
            }

            // 将记录添加到变更记录列表中
            changeRecords.add(source);
            log.info("删除库存处理完成，库存ID: {}", stock.getId());
        } catch (Exception e) {
            log.error("处理删除库存时发生错误", e);
        }
    }

    /**
     * 处理库存变化
     */
    private void handleStockChange(Stock beforeStock, Stock afterStock, ProceedingJoinPoint point, List<CostWeightChangeSource> changeRecords) {
        try {
            log.info("处理库存变化，库存ID: {}", beforeStock.getId());
            log.debug("库存变化详情 - 变化前: {}, 变化后: {}", beforeStock.getCostWeight(), afterStock.getCostWeight());

            // 创建CostWeightChangeSource对象
            CostWeightChangeSource source = new CostWeightChangeSource();
            source.setStockId(beforeStock.getId());
            source.setCommodityId(beforeStock.getCommodityId());
            source.setCommodityName(beforeStock.getCommodityName());
            // 设置规格ID和规格名称
            source.setSpecsId(beforeStock.getSpecsId());
            source.setSpecsName(beforeStock.getSpecsName());
            // 设置库存批次编码
            source.setStockBatchNo(beforeStock.getStockBatchNo());
            source.setBeforeCostWeight(beforeStock.getCostWeight());
            source.setAfterCostWeight(afterStock.getCostWeight());
            source.setChangeAmount(afterStock.getCostWeight().subtract(beforeStock.getCostWeight()));

            // 记录蔬菜单价和包装单价的变化
            source.setBeforeGoodsUnitPrice(beforeStock.getGoodsUnitPrice());
            source.setAfterGoodsUnitPrice(afterStock.getGoodsUnitPrice());
            source.setGoodsUnitPriceChangeAmount(
                    (afterStock.getGoodsUnitPrice() != null ? afterStock.getGoodsUnitPrice() : BigDecimal.ZERO)
                            .subtract(beforeStock.getGoodsUnitPrice() != null ? beforeStock.getGoodsUnitPrice() : BigDecimal.ZERO)
            );
            source.setBeforePackageUnitPrice(beforeStock.getPackageUnitPrice());
            source.setAfterPackageUnitPrice(afterStock.getPackageUnitPrice());
            source.setPackageUnitPriceChangeAmount(
                    (afterStock.getPackageUnitPrice() != null ? afterStock.getPackageUnitPrice() : BigDecimal.ZERO)
                            .subtract(beforeStock.getPackageUnitPrice() != null ? beforeStock.getPackageUnitPrice() : BigDecimal.ZERO)
            );

            source.setSourceType(2); // 入库调整
            source.setOperateTime(new Date());
            source.setOperatorId(getCurrentUserId());
            source.setSourceOrderId(beforeStock.getOrderId());
            source.setSourceOrderType(beforeStock.getStorageType());
            source.setRemark("库存变化");

            // 添加详细的ttid设置日志
            log.debug("开始设置ttid到CostWeightChangeSource对象");
            String traceId = TRACE_TRANSACTION_ID.get();
            log.debug("从TRACE_TRANSACTION_ID获取的traceId: {}", traceId);
            if (traceId != null) {
                source.setTtid(traceId);
                log.info("成功为库存变化设置ttid: {}", traceId);
            } else {
                // 确保链路ID已初始化
                log.warn("TRACE_TRANSACTION_ID为空，尝试初始化");
                getTraceTransactionId();
                traceId = TRACE_TRANSACTION_ID.get();
                log.debug("初始化后获取的traceId: {}", traceId);
                if (traceId != null) {
                    source.setTtid(traceId);
                    log.info("初始化后成功为库存变化设置ttid: {}", traceId);
                } else {
                    log.error("无法为库存变化设置ttid，TRACE_TRANSACTION_ID仍然为空");
                }
            }

            // 将记录添加到变更记录列表中
            changeRecords.add(source);
            log.info("库存变化处理完成，库存ID: {}", beforeStock.getId());
        } catch (Exception e) {
            log.error("处理库存变化时发生错误", e);
        }
    }

    /**
     * 处理新增订单费用
     */
    private void handleNewOrderCost(OrderCost orderCost, ProceedingJoinPoint point, List<CostWeightChangeSource> changeRecords) {
        try {
            log.info("处理新增订单费用，订单费用ID: {}", orderCost.getCostClauseName());
            log.debug("新增订单费用详情: {}", orderCost);

            // 创建CostWeightChangeSource对象
            CostWeightChangeSource source = new CostWeightChangeSource();
            // 通过订单ID查找关联的库存记录来设置stockId和其他字段
            List<Stock> relatedStocks = findRelatedStocksByMainId(orderCost.getMainId());
            if (!relatedStocks.isEmpty()) {
                Stock relatedStock = relatedStocks.get(0);
                source.setStockId(relatedStock.getId());
                source.setCommodityId(relatedStock.getCommodityId());
                source.setCommodityName(relatedStock.getCommodityName());
                // 设置规格ID和规格名称
                source.setSpecsId(relatedStock.getSpecsId());
                source.setSpecsName(relatedStock.getSpecsName());
                // 设置库存批次编码
                source.setStockBatchNo(relatedStock.getStockBatchNo());
                source.setBeforeCostWeight(relatedStock.getCostWeight());
                source.setAfterCostWeight(relatedStock.getCostWeight());
                source.setChangeAmount(BigDecimal.ZERO);

                // 记录蔬菜单价和包装单价（保持不变）
                source.setBeforeGoodsUnitPrice(relatedStock.getGoodsUnitPrice());
                source.setAfterGoodsUnitPrice(relatedStock.getGoodsUnitPrice());
                source.setGoodsUnitPriceChangeAmount(BigDecimal.ZERO);
                source.setBeforePackageUnitPrice(relatedStock.getPackageUnitPrice());
                source.setAfterPackageUnitPrice(relatedStock.getPackageUnitPrice());
                source.setPackageUnitPriceChangeAmount(BigDecimal.ZERO);
            }
            source.setSourceType(5); // 订单费用统计
            source.setChangeAmount(orderCost.getMoney());
            source.setOperateTime(new Date());
            source.setOperatorId(getCurrentUserId());
            source.setSourceOrderId(orderCost.getMainId());
            source.setRemark("新增订单费用");

            // 添加详细的ttid设置日志
            log.debug("开始设置ttid到CostWeightChangeSource对象");
            String traceId = TRACE_TRANSACTION_ID.get();
            log.debug("从TRACE_TRANSACTION_ID获取的traceId: {}", traceId);
            if (traceId != null) {
                source.setTtid(traceId);
                log.info("成功为新增订单费用设置ttid: {}", traceId);
            } else {
                // 确保链路ID已初始化
                log.warn("TRACE_TRANSACTION_ID为空，尝试初始化");
                getTraceTransactionId();
                traceId = TRACE_TRANSACTION_ID.get();
                log.debug("初始化后获取的traceId: {}", traceId);
                if (traceId != null) {
                    source.setTtid(traceId);
                    log.info("初始化后成功为新增订单费用设置ttid: {}", traceId);
                } else {
                    log.error("无法为新增订单费用设置ttid，TRACE_TRANSACTION_ID仍然为空");
                }
            }

            // 将记录添加到变更记录列表中
            changeRecords.add(source);
            log.info("新增订单费用处理完成，订单费用ID: {}", orderCost.getCostClauseName());
        } catch (Exception e) {
            log.error("处理新增订单费用时发生错误", e);
        }
    }

    /**
     * 处理删除订单费用
     */
    private void handleDeletedOrderCost(OrderCost orderCost, ProceedingJoinPoint point, List<CostWeightChangeSource> changeRecords) {
        try {
            log.info("处理删除订单费用，订单费用ID: {}", orderCost.getCostClauseName());
            log.debug("删除订单费用详情: {}", orderCost);

            // 创建CostWeightChangeSource对象
            CostWeightChangeSource source = new CostWeightChangeSource();
            // 通过订单ID查找关联的库存记录来设置stockId和其他字段
            List<Stock> relatedStocks = findRelatedStocksByMainId(orderCost.getMainId());
            if (!relatedStocks.isEmpty()) {
                Stock relatedStock = relatedStocks.get(0);
                source.setStockId(relatedStock.getId());
                source.setCommodityId(relatedStock.getCommodityId());
                source.setCommodityName(relatedStock.getCommodityName());
                // 设置规格ID和规格名称
                source.setSpecsId(relatedStock.getSpecsId());
                source.setSpecsName(relatedStock.getSpecsName());
                // 设置库存批次编码
                source.setStockBatchNo(relatedStock.getStockBatchNo());
                source.setBeforeCostWeight(relatedStock.getCostWeight());
                source.setAfterCostWeight(relatedStock.getCostWeight());
                source.setChangeAmount(BigDecimal.ZERO);

                // 记录蔬菜单价和包装单价（保持不变）
                source.setBeforeGoodsUnitPrice(relatedStock.getGoodsUnitPrice());
                source.setAfterGoodsUnitPrice(relatedStock.getGoodsUnitPrice());
                source.setGoodsUnitPriceChangeAmount(BigDecimal.ZERO);
                source.setBeforePackageUnitPrice(relatedStock.getPackageUnitPrice());
                source.setAfterPackageUnitPrice(relatedStock.getPackageUnitPrice());
                source.setPackageUnitPriceChangeAmount(BigDecimal.ZERO);
            }
            source.setSourceType(5); // 订单费用统计
            source.setChangeAmount(orderCost.getMoney().negate());
            source.setOperateTime(new Date());
            source.setOperatorId(getCurrentUserId());
            source.setSourceOrderId(orderCost.getMainId());
            source.setRemark("删除订单费用");

            // 将记录添加到变更记录列表中
            changeRecords.add(source);
            log.info("删除订单费用处理完成，订单费用ID: {}", orderCost.getCostClauseName());
        } catch (Exception e) {
            log.error("处理删除订单费用时发生错误", e);
        }
    }

    /**
     * 处理订单费用变化
     */
    private void handleOrderCostChange(OrderCost beforeOrderCost, OrderCost afterOrderCost, ProceedingJoinPoint point, List<CostWeightChangeSource> changeRecords) {
        try {
            log.info("处理订单费用变化，订单费用ID: {}", beforeOrderCost.getCostClauseName());
            log.debug("订单费用变化详情 - 变化前: {}, 变化后: {}", beforeOrderCost.getMoney(), afterOrderCost.getMoney());

            // 创建CostWeightChangeSource对象
            CostWeightChangeSource source = new CostWeightChangeSource();
            // 通过订单ID查找关联的库存记录来设置stockId和其他字段
            List<Stock> relatedStocks = findRelatedStocksByMainId(beforeOrderCost.getMainId());
            if (!relatedStocks.isEmpty()) {
                Stock relatedStock = relatedStocks.get(0);
                source.setStockId(relatedStock.getId());
                source.setCommodityId(relatedStock.getCommodityId());
                source.setCommodityName(relatedStock.getCommodityName());
                // 设置规格ID和规格名称
                source.setSpecsId(relatedStock.getSpecsId());
                source.setSpecsName(relatedStock.getSpecsName());
                // 设置库存批次编码
                source.setStockBatchNo(relatedStock.getStockBatchNo());
                source.setBeforeCostWeight(relatedStock.getCostWeight());
                source.setAfterCostWeight(relatedStock.getCostWeight());
                source.setChangeAmount(BigDecimal.ZERO);

                // 记录蔬菜单价和包装单价（保持不变）
                source.setBeforeGoodsUnitPrice(relatedStock.getGoodsUnitPrice());
                source.setAfterGoodsUnitPrice(relatedStock.getGoodsUnitPrice());
                source.setGoodsUnitPriceChangeAmount(BigDecimal.ZERO);
                source.setBeforePackageUnitPrice(relatedStock.getPackageUnitPrice());
                source.setAfterPackageUnitPrice(relatedStock.getPackageUnitPrice());
                source.setPackageUnitPriceChangeAmount(BigDecimal.ZERO);
            }
            source.setSourceType(5); // 订单费用统计
            source.setChangeAmount(afterOrderCost.getMoney().subtract(beforeOrderCost.getMoney()));
            source.setOperateTime(new Date());
            source.setOperatorId(getCurrentUserId());
            source.setSourceOrderId(beforeOrderCost.getMainId());
            source.setRemark("订单费用变化");

            // 添加详细的ttid设置日志
            log.debug("开始设置ttid到CostWeightChangeSource对象");
            String traceId = TRACE_TRANSACTION_ID.get();
            log.debug("从TRACE_TRANSACTION_ID获取的traceId: {}", traceId);
            if (traceId != null) {
                source.setTtid(traceId);
                log.info("成功为订单费用变化设置ttid: {}", traceId);
            } else {
                // 确保链路ID已初始化
                log.warn("TRACE_TRANSACTION_ID为空，尝试初始化");
                getTraceTransactionId();
                traceId = TRACE_TRANSACTION_ID.get();
                log.debug("初始化后获取的traceId: {}", traceId);
                if (traceId != null) {
                    source.setTtid(traceId);
                    log.info("初始化后成功为订单费用变化设置ttid: {}", traceId);
                } else {
                    log.error("无法为订单费用变化设置ttid，TRACE_TRANSACTION_ID仍然为空");
                }
            }

            // 创建订单费用变化DTO并转换为JSON
            OrderCostChangeDTO orderCostChangeDTO = new OrderCostChangeDTO();
            orderCostChangeDTO.setCostName(beforeOrderCost.getCostClauseName());
            orderCostChangeDTO.setBeforeCost(beforeOrderCost.getMoney());
            orderCostChangeDTO.setAfterCost(afterOrderCost.getMoney());
            orderCostChangeDTO.setCostChange(afterOrderCost.getMoney().subtract(beforeOrderCost.getMoney()));

            if (beforeOrderCost != null) {
                orderCostChangeDTO.setCostId(beforeOrderCost.getId());
                orderCostChangeDTO.setMainId(beforeOrderCost.getMainId());
            } else if (afterOrderCost != null) {
                orderCostChangeDTO.setCostId(afterOrderCost.getId());
                orderCostChangeDTO.setMainId(afterOrderCost.getMainId());
            }

            // 将订单费用变化信息转换为JSON字符串存储
            try {
                String orderCostChangesJson = com.alibaba.fastjson.JSON.toJSONString(orderCostChangeDTO);
                source.setOrderCostChanges(orderCostChangesJson);
            } catch (Exception e) {
                log.warn("转换订单费用变化信息为JSON时发生错误", e);
            }

            // 将记录添加到变更记录列表中
            changeRecords.add(source);
            log.info("订单费用变化处理完成，订单费用ID: {}", beforeOrderCost.getCostClauseName());
        } catch (Exception e) {
            log.error("处理订单费用变化时发生错误", e);
        }
    }


    /**
     * 处理连锁变化
     */
    private void handleChainCostChange(CostWeightChangeSource source, ProceedingJoinPoint point) {
        try {
            log.info("处理连锁变化，源ID: {}", source.getId());
            log.debug("连锁变化详情: {}", source);
            
            // 确保在处理连锁变化时ttid已设置
            if (source.getTtid() == null) {
                String traceId = TRACE_TRANSACTION_ID.get();
                if (traceId != null) {
                    source.setTtid(traceId);
                    log.debug("为连锁变化设置ttid: {}", traceId);
                } else {
                    log.warn("无法为连锁变化设置ttid，TRACE_TRANSACTION_ID为空");
                }
            }
            
            // 处理连锁变化
            chainCostChangeService.findAllAndHandleChainChanges(source);
            
            log.info("连锁变化处理完成，源ID: {}", source.getId());
        } catch (Exception e) {
            log.error("处理连锁变化时发生错误", e);
        }
    }
    
    /**
     * 获取当前用户信息
     */
    private SysUserEntity getCurrentUser() {
        try {
            return (SysUserEntity) SecurityUtils.getSubject().getPrincipal();
        } catch (Exception e) {
            log.warn("获取当前用户信息失败", e);
            return null;
        }
    }
    
    /**
     * 获取当前用户ID
     */
    private Long getCurrentUserId() {
        SysUserEntity user = getCurrentUser();
        if(Objects.isNull(user)){
            log.error("获取当前用户id失败");
            return 1L;
        }else{
            return user.getUserId();
        }
    }
    
    /**
     * 设置操作人信息
     */
    private void setOperatorInfo(CostWeightChangeSource changeSource) {
        SysUserEntity user = getCurrentUser();
        if (user != null) {
            changeSource.setOperatorId(user.getUserId());
            changeSource.setOperatorName(user.getRealName());
        } else {
            changeSource.setOperatorId(1L);
            changeSource.setOperatorName("系统");
        }
    }
    
    /**
     * 检查CostWeight是否发生变化
     */
    private boolean hasCostWeightChanged(Stock beforeStock, Stock afterStock) {
        if (beforeStock.getCostWeight() == null && afterStock.getCostWeight() == null) {
            log.debug("库存CostWeight比较 - 两者都为null，无变化");
            return false;
        }
        if (beforeStock.getCostWeight() == null || afterStock.getCostWeight() == null) {
            log.debug("库存CostWeight比较 - 其中一个为null，有变化，变化前: {}, 变化后: {}", 
                     beforeStock.getCostWeight(), afterStock.getCostWeight());
            return true;
        }
        boolean changed = beforeStock.getCostWeight().compareTo(afterStock.getCostWeight()) != 0;
        if (changed) {
            log.debug("库存CostWeight比较 - 值发生变化，变化前: {}, 变化后: {}", 
                     beforeStock.getCostWeight(), afterStock.getCostWeight());
        } else {
            log.debug("库存CostWeight比较 - 值未发生变化，当前值: {}", beforeStock.getCostWeight());
        }
        return changed;
    }
    /**
     * 检查金额是否发生变化
     */
    private boolean hasMoneyChanged(OrderCost beforeOrderCost, OrderCost afterOrderCost) {
        if (beforeOrderCost.getMoney() == null && afterOrderCost.getMoney() == null) {
            log.debug("订单费用金额比较 - 两者都为null，无变化");
            return false;
        }
        if (beforeOrderCost.getMoney() == null || afterOrderCost.getMoney() == null) {
            log.debug("订单费用金额比较 - 其中一个为null，有变化，变化前: {}, 变化后: {}", 
                     beforeOrderCost.getMoney(), afterOrderCost.getMoney());
            return true;
        }
        boolean changed = beforeOrderCost.getMoney().compareTo(afterOrderCost.getMoney()) != 0;
        if (changed) {
            log.debug("订单费用金额比较 - 值发生变化，变化前: {}, 变化后: {}", 
                     beforeOrderCost.getMoney(), afterOrderCost.getMoney());
        } else {
            log.debug("订单费用金额比较 - 值未发生变化，当前值: {}", beforeOrderCost.getMoney());
        }
        return changed;
    }
    
    /**
     * 清理标记和数据
     */
    private void cleanup() {
        IN_COST_WEIGHT_ASPECT.remove();
        BEFORE_EXECUTION_DATA.remove();
        TRACE_TRANSACTION_ID.remove();
        TTID_INITIALIZED.remove();
    }
    
    /**
     * 清理异步线程中的ThreadLocal变量
     */
    private void cleanupThreadLocals() {
        IN_COST_WEIGHT_ASPECT.remove();
        BEFORE_EXECUTION_DATA.remove();
        TRACE_TRANSACTION_ID.remove();
        TTID_INITIALIZED.remove();
    }
    
    /**
     * 获取事务ID
     */
    private String getTraceTransactionId() {
        log.debug("开始获取事务ID，TTID_INITIALIZED状态: {}", TTID_INITIALIZED.get());
        if (TTID_INITIALIZED.get() == null || !TTID_INITIALIZED.get()) {
            String transactionId = UUID.randomUUID().toString();
            TRACE_TRANSACTION_ID.set(transactionId);
            TTID_INITIALIZED.set(true);
            log.info("初始化事务ID: {}", transactionId);
        }
        String traceId = TRACE_TRANSACTION_ID.get();
        log.debug("获取到的事务ID: {}", traceId);
        return traceId;
    }
    /**
     * 记录CostWeight变化源头
     */
    private void recordCostWeightChangeSource(Stock beforeStock, Stock afterStock, ProceedingJoinPoint point, Object[] args) {
        try {
            CostWeightChangeSource changeSource = new CostWeightChangeSource();
            changeSource.setStockId(beforeStock.getId());
            changeSource.setCommodityId(beforeStock.getCommodityId());
            changeSource.setCommodityName(beforeStock.getCommodityName());
            // 设置规格ID和规格名称
            changeSource.setSpecsId(beforeStock.getSpecsId());
            changeSource.setSpecsName(beforeStock.getSpecsName());
            // 设置库存批次编码
            changeSource.setStockBatchNo(beforeStock.getStockBatchNo());
            changeSource.setBeforeCostWeight(beforeStock.getCostWeight());
            changeSource.setAfterCostWeight(afterStock.getCostWeight());
            changeSource.setChangeAmount(afterStock.getCostWeight().subtract(beforeStock.getCostWeight()));
            
            // 记录蔬菜单价和包装单价的变化
            BigDecimal beforeGoodsUnitPrice = beforeStock.getGoodsUnitPrice() != null ? beforeStock.getGoodsUnitPrice() : BigDecimal.ZERO;
            BigDecimal afterGoodsUnitPrice = afterStock.getGoodsUnitPrice() != null ? afterStock.getGoodsUnitPrice() : BigDecimal.ZERO;
            BigDecimal beforePackageUnitPrice = beforeStock.getPackageUnitPrice() != null ? beforeStock.getPackageUnitPrice() : BigDecimal.ZERO;
            BigDecimal afterPackageUnitPrice = afterStock.getPackageUnitPrice() != null ? afterStock.getPackageUnitPrice() : BigDecimal.ZERO;
            
            changeSource.setBeforeGoodsUnitPrice(beforeGoodsUnitPrice);
            changeSource.setAfterGoodsUnitPrice(afterGoodsUnitPrice);
            changeSource.setGoodsUnitPriceChangeAmount(afterGoodsUnitPrice.subtract(beforeGoodsUnitPrice));
            changeSource.setBeforePackageUnitPrice(beforePackageUnitPrice);
            changeSource.setAfterPackageUnitPrice(afterPackageUnitPrice);
            changeSource.setPackageUnitPriceChangeAmount(afterPackageUnitPrice.subtract(beforePackageUnitPrice));
            
            // 使用已初始化的追踪事务ID
            String traceId5 = TRACE_TRANSACTION_ID.get();
            log.debug("从TRACE_TRANSACTION_ID获取的traceId5: {}", traceId5);
            if (traceId5 != null) {
                changeSource.setTtid(traceId5);
                log.debug("使用已存在的traceId设置ttid: {}", traceId5);
            } else {
                // 确保链路ID已初始化
                log.debug("TRACE_TRANSACTION_ID为空，调用getTraceTransactionId()初始化");
                getTraceTransactionId();
                traceId5 = TRACE_TRANSACTION_ID.get();
                log.debug("初始化后获取的traceId5: {}", traceId5);
                if (traceId5 != null) {
                    changeSource.setTtid(traceId5);
                    log.debug("使用新初始化的traceId设置ttid: {}", traceId5);
                } else {
                    log.warn("TRACE_TRANSACTION_ID 为 null，未能设置 ttid");
                }
            }
            
            changeSource.setOperateTime(new Date());
            
            // 设置操作人信息
            setOperatorInfo(changeSource);
            
            // 分析变化源头
            analyzeChangeSource(changeSource, point, args);
            
            // 保存记录
            costWeightChangeSourceService.saveOrUpdate(changeSource);
            
            // 将当前变化加入追踪链
            addToChangeChain(changeSource);
            
            // 查找并处理所有连锁变化
            chainCostChangeService.findAllAndHandleChainChanges(changeSource);
            
            // 分析订单费用变化（在保存成本变化记录后再分析订单费用变化）
            analyzeOrderCostChanges(changeSource, beforeStock, afterStock);
        } catch (Exception e) {
            log.error("记录CostWeight变化源头时发生错误", e);
        }
    }
    
    /**
     * 分析订单费用变化
     */
    private void analyzeOrderCostChanges(CostWeightChangeSource changeSource, Stock beforeStock, Stock afterStock) {
        try {
            // 确保链路ID已初始化
            getTraceTransactionId();
            
            log.info("开始分析订单费用变化，库存ID: {}, detailId: {}", 
                beforeStock != null ? beforeStock.getId() : "null", 
                beforeStock != null ? beforeStock.getDetailId() : "null");
            
            // 通过库存的detailId查找相关的订单费用
            if (beforeStock != null && beforeStock.getDetailId() != null) {
                log.info("库存detailId不为空，开始查找订单费用，detailId: {}", beforeStock.getDetailId());
                // 查找与该detailId关联的订单费用（需要通过订单ID和detailId共同查询）
                List<OrderCost> beforeOrderCosts = findOrderCostsByDetailId(beforeStock.getDetailId());
                if (beforeOrderCosts != null && !beforeOrderCosts.isEmpty()) {
                    log.info("发现 {} 条订单费用记录与库存ID {} 关联", beforeOrderCosts.size(), beforeStock.getId());
                    
                    // 查询更新后的订单费用（在原方法执行完成后再查询）
                    List<OrderCost> afterOrderCosts = findOrderCostsByDetailId(beforeStock.getDetailId());
                    
                    // 使用改进的方法分析订单费用变化
                    analyzeOrderCostChangesWithCapturedStates(
                        changeSource, beforeStock, beforeOrderCosts, afterOrderCosts);
                } else {
                    log.info("未发现与库存ID {} 关联的订单费用记录", beforeStock.getId());
                }
            } else {
                log.info("库存detailId为空，跳过订单费用分析");
            }
        } catch (Exception e) {
            log.error("分析订单费用变化时发生错误", e);
        }
    }
    
    /**
     * 分析变化源头
     */
    private void analyzeChangeSource(CostWeightChangeSource changeSource, ProceedingJoinPoint point, Object[] args) {
        try {
            // 获取方法名
            String methodName = point.getSignature().getName();
            // 获取类名
            String className = point.getTarget().getClass().getSimpleName();
            
            // 将方法名和类名信息存储在remark字段中
            changeSource.setRemark("方法: " + methodName + ", 类: " + className);
            
            // 将参数信息存储在detailInfo字段中
            StringBuilder detailInfo = new StringBuilder();
            if (changeSource.getDetailInfo() != null) {
                detailInfo.append(changeSource.getDetailInfo());
            }
            detailInfo.append("参数信息: ");
            for (Object arg : args) {
                if (arg != null) {
                    detailInfo.append(arg).append(", ");
                } else {
                    detailInfo.append("null, ");
                }
            }
            if (detailInfo.length() > 0 && detailInfo.toString().endsWith(", ")) {
                detailInfo.setLength(detailInfo.length() - 2); // 去掉最后一个逗号和空格
            }
            changeSource.setDetailInfo(detailInfo.toString());
            
            log.info("分析变化源头完成，方法: {}, 类: {}, 参数数量: {}", methodName, className, args != null ? args.length : 0);
        } catch (Exception e) {
            log.error("分析变化源头时发生错误", e);
        }
    }
    
    /**
     * 查找关联的入库订单
     */
    private void findRelatedInboundOrder(CostWeightChangeSource changeSource, Object[] args) {
        try {
            // 遍历参数，查找AgentDelivery对象
            for (Object arg : args) {
                if (arg instanceof AgentDelivery) {
                    AgentDelivery delivery = (AgentDelivery) arg;
                    changeSource.setSourceOrderId(delivery.getId());
                    changeSource.setSourceOrderNo(delivery.getDocNo());
                    changeSource.setSourceOrderType(1); // 代办交货
                    
                    // 查找关联商品（打包原料）
                    findRelatedCommodity(changeSource, delivery);
                    break;
                }
            }
        } catch (Exception e) {
            log.error("查找关联入库订单时发生错误", e);
        }
    }
    
    /**
     * 查找关联的出库订单
     */
    private void findRelatedOutboundOrder(CostWeightChangeSource changeSource, Object[] args) {
        try {
            // 遍历参数，查找出库相关信息
            for (Object arg : args) {
                if (arg instanceof Long && changeSource.getSourceOrderId() == null) {
                    Long orderId = (Long) arg;
                    // 这里可以进一步查询订单信息
                    changeSource.setSourceOrderId(orderId);
                    changeSource.setSourceOrderType(7); // 销售出库
                    break;
                }
            }
            
            // 查找关联的销售订单明细库存记录
            if (changeSource.getStockId() != null) {
                QueryWrapper<SalesOrderDetailStock> queryWrapper = new QueryWrapper<>();
                queryWrapper.eq("stock_id", changeSource.getStockId());
                List<SalesOrderDetailStock> detailStocks = salesOrderDetailStockService.list(queryWrapper);
                if (!detailStocks.isEmpty()) {
                    SalesOrderDetailStock detailStock = detailStocks.get(0);
                    changeSource.setSourceOrderId(detailStock.getDetailId()); // 修正：使用getDetailId()而不是getSalesOrderDetailId()
                    changeSource.setSourceOrderType(7); // 销售出库
                }
            }
        } catch (Exception e) {
            log.error("查找关联出库订单时发生错误", e);
        }
    }
    
    /**
     * 查找关联订单（针对updateStock方法）
     */
    private void findRelatedOrderForUpdateStock(CostWeightChangeSource changeSource, Object[] args) {
        try {
            // 查找StockUpdatePO参数
            for (Object arg : args) {
                // 这里可以根据具体业务逻辑进一步分析
                // 暂时留空，后续可以根据具体需求完善
            }
            
            // 通过库存ID查找关联的订单信息
            if (changeSource.getStockId() != null) {
                Stock stock = stockService.selectById(changeSource.getStockId());
                if (stock != null) {
                    changeSource.setSourceOrderId(stock.getOrderId());
                }
            }
        } catch (Exception e) {
            log.error("查找关联订单时发生错误", e);
        }
    }
    
    /**
     * 查找关联订单（针对updateStockByDetailId方法）
     */
    private void findRelatedOrderForUpdateStockByDetailId(CostWeightChangeSource changeSource, Object[] args) {
        try {
            // updateStockByDetailId方法参数: BigDecimal nowCostWeight, Long detailId, Long orderId
            if (args.length >= 3 && args[1] instanceof Long && args[2] instanceof Long) {
                Long detailId = (Long) args[1];
                Long orderId = (Long) args[2];
                
                changeSource.setSourceOrderId(orderId);
                // 可以进一步查询订单信息来设置订单编号等信息
                // 暂时留空，后续可以根据具体需求完善
            }
        } catch (Exception e) {
            log.error("查找关联订单时发生错误", e);
        }
    }
    
    /**
     * 查找关联的采购订单
     */
    private void findRelatedPurchaseOrder(CostWeightChangeSource changeSource, Object[] args) {
        try {
            // 遍历参数，查找PurchaseDelivery对象
            for (Object arg : args) {
                if (arg instanceof PurchaseDelivery) {
                    PurchaseDelivery delivery = (PurchaseDelivery) arg;
                    changeSource.setSourceOrderId(delivery.getId());
                    changeSource.setSourceOrderNo(delivery.getDocNo());
                    changeSource.setSourceOrderType(2); // 采购收货
                    break;
                }
            }
        } catch (Exception e) {
            log.error("查找关联采购订单时发生错误", e);
        }
    }

    /**
     * 查找关联的代办交货订单
     */
    private void findRelatedAgentDeliveryOrder(CostWeightChangeSource changeSource, Object[] args) {
        try {
            // 遍历参数，查找AgentDelivery对象
            for (Object arg : args) {
                if (arg instanceof AgentDelivery) {
                    AgentDelivery delivery = (AgentDelivery) arg;
                    changeSource.setSourceOrderId(delivery.getId());
                    changeSource.setSourceOrderNo(delivery.getDocNo());
                    changeSource.setSourceOrderType(1); // 代办交货
                    
                    // 查找关联商品（打包原料）
                    findRelatedCommodity(changeSource, delivery);
                    break;
                }
            }
        } catch (Exception e) {
            log.error("查找关联代办交货订单时发生错误", e);
        }
    }
    
    /**
     * 查找关联商品（打包原料）
     */
    private void findRelatedCommodity(CostWeightChangeSource changeSource, AgentDelivery delivery) {
        try {
            // 如果有商品详情，设置关联商品信息
            if (delivery.getCommodities() != null && !delivery.getCommodities().isEmpty()) {
                AgentDeliveryDetail detail = delivery.getCommodities().get(0);
                changeSource.setRelatedCommodityId(detail.getCommodityId());
                changeSource.setRelatedCommodityName(detail.getCommodityName());
            }
        } catch (Exception e) {
            log.error("查找关联商品时发生错误", e);
        }
    }
    
    /**
     * 查找关联的订单费用
     */
    private List<OrderCost> findOrderCostsByDetailId(Long detailId) {
        try {
            // 根据detailId查找关联的订单费用
            // 这里需要根据业务逻辑确定如何查找关联的订单费用
            if (detailId != null) {
                // 假设通过detailId可以找到关联的订单费用
                // 实际实现需要根据具体的业务逻辑来确定
                return orderCostService.selectByMainId(detailId);
            }
            return new ArrayList<>();
        } catch (Exception e) {
            log.error("查找关联订单费用时发生错误", e);
            return new ArrayList<>();
        }
    }
    
    /**
     * 查找关联的库存记录
     */
    private List<Stock> findRelatedStocksByMainId(Long mainId) {
        try {
            // 根据mainId查找关联的库存记录
            if (mainId != null) {
                return stockService.queryStockByOrderId(mainId);
            }
            return new ArrayList<>();
        } catch (Exception e) {
            log.error("查找关联库存记录时发生错误", e);
            return new ArrayList<>();
        }
    }
    
    /**
     * 分析订单费用变化（使用已捕获的状态）
     */
    private void analyzeOrderCostChangesWithCapturedStates(CostWeightChangeSource changeSource, Stock beforeStock, 
            List<OrderCost> beforeOrderCosts, List<OrderCost> afterOrderCosts) {
        try {
            // 确保链路ID已初始化
            getTraceTransactionId();
            
            log.info("分析订单费用变化，库存ID: {}", beforeStock.getId());
            
            // 如果变化前或变化后的订单费用状态为空，则创建空列表
            if (beforeOrderCosts == null) {
                beforeOrderCosts = new ArrayList<>();
            }
            if (afterOrderCosts == null) {
                afterOrderCosts = new ArrayList<>();
            }
            
            // 创建费用条款ID到金额的映射，便于比较
            Map<Long, BigDecimal> beforeCostMap = new HashMap<>();
            Map<Long, BigDecimal> afterCostMap = new HashMap<>();
            Map<Long, OrderCost> beforeCostDetailMap = new HashMap<>();
            Map<Long, OrderCost> afterCostDetailMap = new HashMap<>();
            
            // 填充变化前的费用映射
            for (OrderCost cost : beforeOrderCosts) {
                if (cost.getCostClauseId() != null) {
                    beforeCostMap.put(cost.getCostClauseId(), 
                        cost.getMoney() != null ? cost.getMoney() : BigDecimal.ZERO);
                    beforeCostDetailMap.put(cost.getCostClauseId(), cost);
                }
            }
            
            // 填充变化后的费用映射
            for (OrderCost cost : afterOrderCosts) {
                if (cost.getCostClauseId() != null) {
                    afterCostMap.put(cost.getCostClauseId(), 
                        cost.getMoney() != null ? cost.getMoney() : BigDecimal.ZERO);
                    afterCostDetailMap.put(cost.getCostClauseId(), cost);
                }
            }
            
            // 检查所有费用条款ID的变化
            Set<Long> allCostClauseIds = new HashSet<>();
            allCostClauseIds.addAll(beforeCostMap.keySet());
            allCostClauseIds.addAll(afterCostMap.keySet());
            
            log.info("检查 {} 种费用条款的变化", allCostClauseIds.size());
            
            boolean hasCostChanges = false;
            
            // 检查每种费用条款的变化
            for (Long costClauseId : allCostClauseIds) {
                BigDecimal beforeAmount = beforeCostMap.getOrDefault(costClauseId, BigDecimal.ZERO);
                BigDecimal afterAmount = afterCostMap.getOrDefault(costClauseId, BigDecimal.ZERO);
                
                // 比较金额是否有变化
                if (beforeAmount.compareTo(afterAmount) != 0) {
                    String costClauseName = beforeCostDetailMap.containsKey(costClauseId) ? 
                        beforeCostDetailMap.get(costClauseId).getCostClauseName() : 
                        (afterCostDetailMap.containsKey(costClauseId) ? 
                            afterCostDetailMap.get(costClauseId).getCostClauseName() : "未知费用");
                    log.info("检查费用条款: {}, 费用名称: {}, 变化前: {}, 变化后: {}", costClauseId, costClauseName, beforeAmount, afterAmount);
                    hasCostChanges = true;
                    
                    // 记录费用变化到成本变化源头
                    recordOrderCostChange(changeSource, beforeStock, costClauseName, beforeAmount, afterAmount,
                        beforeCostDetailMap.get(costClauseId), afterCostDetailMap.get(costClauseId));
                } else {
                    String costClauseName = beforeCostDetailMap.containsKey(costClauseId) ? 
                        beforeCostDetailMap.get(costClauseId).getCostClauseName() : "未知费用";
                    log.info("订单费用条款 '{}' 未发生变化", costClauseName);
                }
            }
            
            // 检查是否有新增的费用条款
            Set<Long> newCostClauseIds = new HashSet<>(afterCostMap.keySet());
            newCostClauseIds.removeAll(beforeCostMap.keySet());
            for (Long newCostClauseId : newCostClauseIds) {
                BigDecimal amount = afterCostMap.get(newCostClauseId);
                String costClauseName = afterCostDetailMap.containsKey(newCostClauseId) ? 
                    afterCostDetailMap.get(newCostClauseId).getCostClauseName() : "未知费用";
                log.info("发现新增费用条款: {}, 费用名称: {}, 金额: {}", newCostClauseId, costClauseName, amount);
                hasCostChanges = true;
                
                // 记录新增费用到成本变化源头
                recordOrderCostChange(changeSource, beforeStock, costClauseName, BigDecimal.ZERO, amount,
                    null, afterCostDetailMap.get(newCostClauseId));
            }
            
            // 检查是否有删除的费用条款
            Set<Long> removedCostClauseIds = new HashSet<>(beforeCostMap.keySet());
            removedCostClauseIds.removeAll(afterCostMap.keySet());
            for (Long removedCostClauseId : removedCostClauseIds) {
                BigDecimal amount = beforeCostMap.get(removedCostClauseId);
                String costClauseName = beforeCostDetailMap.containsKey(removedCostClauseId) ? 
                    beforeCostDetailMap.get(removedCostClauseId).getCostClauseName() : "未知费用";
                log.info("发现删除费用条款: {}, 费用名称: {}, 金额: {}", removedCostClauseId, costClauseName, amount);
                hasCostChanges = true;
                
                // 记录删除费用到成本变化源头
                recordOrderCostChange(changeSource, beforeStock, costClauseName, amount, BigDecimal.ZERO,
                    beforeCostDetailMap.get(removedCostClauseId), null);
            }
            
            if (hasCostChanges) {
                log.info("检测到订单费用变化，准备记录变化源头");
                // 如果有费用变化，记录变化源头
                recordOrderCostChangeSource(changeSource, beforeStock);
            } else {
                log.info("未检测到订单费用变化");
            }
        } catch (Exception e) {
            log.error("分析订单费用变化时发生错误，库存ID: {}", beforeStock != null ? beforeStock.getId() : "unknown", e);
        }
    }
    
    /**
     * 记录订单费用变化到成本变化源头
     */
    private void recordOrderCostChange(CostWeightChangeSource changeSource, Stock beforeStock, 
            String costType, BigDecimal beforeAmount, BigDecimal afterAmount, 
            OrderCost beforeCostDetail, OrderCost afterCostDetail) {
        try {
            log.info("记录订单费用变化，费用类型: {}, 变化前: {}, 变化后: {}", costType, beforeAmount, afterAmount);
            
            // 计算变化差额
            BigDecimal changeAmount = afterAmount.subtract(beforeAmount);
            
            // 创建一个新的成本变化记录
            CostWeightChangeSource costChange = new CostWeightChangeSource();
            costChange.setStockId(beforeStock.getId());
            costChange.setCommodityId(beforeStock.getCommodityId());
            costChange.setCommodityName(beforeStock.getCommodityName() + " - " + costType);
            // 设置规格ID和规格名称
            costChange.setSpecsId(beforeStock.getSpecsId());
            costChange.setSpecsName(beforeStock.getSpecsName());
            // 设置库存批次编码
            costChange.setStockBatchNo(beforeStock.getStockBatchNo());
            costChange.setBeforeCostWeight(beforeStock.getCostWeight());
            costChange.setAfterCostWeight(beforeStock.getCostWeight()); // 订单费用变化不直接影响成本单价
            costChange.setChangeAmount(BigDecimal.ZERO); // 订单费用变化不直接影响成本单价
            
            // 记录蔬菜单价和包装单价（保持不变）
            costChange.setBeforeGoodsUnitPrice(beforeStock.getGoodsUnitPrice());
            costChange.setAfterGoodsUnitPrice(beforeStock.getGoodsUnitPrice());
            costChange.setGoodsUnitPriceChangeAmount(BigDecimal.ZERO);
            costChange.setBeforePackageUnitPrice(beforeStock.getPackageUnitPrice());
            costChange.setAfterPackageUnitPrice(beforeStock.getPackageUnitPrice());
            costChange.setPackageUnitPriceChangeAmount(BigDecimal.ZERO);
            
            // 设置订单费用相关信息
            costChange.setSourceType(5); // 订单费用变化
            costChange.setRemark("订单费用 '" + costType + "' 发生变化");
            
            // 创建订单费用变化DTO并转换为JSON
            OrderCostChangeDTO orderCostChangeDTO = new OrderCostChangeDTO();
            orderCostChangeDTO.setCostName(costType);
            orderCostChangeDTO.setBeforeCost(beforeAmount);
            orderCostChangeDTO.setAfterCost(afterAmount);
            orderCostChangeDTO.setCostChange(changeAmount);
            
            if (beforeCostDetail != null) {
                orderCostChangeDTO.setCostId(beforeCostDetail.getId());
                orderCostChangeDTO.setMainId(beforeCostDetail.getMainId());
            } else if (afterCostDetail != null) {
                orderCostChangeDTO.setCostId(afterCostDetail.getId());
                orderCostChangeDTO.setMainId(afterCostDetail.getMainId());
            }
            
            // 将订单费用变化信息转换为JSON字符串存储
            try {
                String orderCostChangesJson = com.alibaba.fastjson.JSON.toJSONString(orderCostChangeDTO);
                costChange.setOrderCostChanges(orderCostChangesJson);
            } catch (Exception e) {
                log.warn("转换订单费用变化信息为JSON时发生错误", e);
            }
            
            // 添加详细信息（保持原有逻辑）
            StringBuilder detailInfo = new StringBuilder();
            detailInfo.append("费用类型: ").append(costType).append("\n");
            detailInfo.append("变化前金额: ").append(beforeAmount).append("\n");
            detailInfo.append("变化后金额: ").append(afterAmount).append("\n");
            detailInfo.append("变化差额: ").append(changeAmount).append("\n");
            
            // 添加费用详情信息
            if (beforeCostDetail != null) {
                detailInfo.append("变化前费用详情:\n");
                detailInfo.append("  费用ID: ").append(beforeCostDetail.getId()).append("\n");
                detailInfo.append("  费用名称: ").append(beforeCostDetail.getCostClauseName()).append("\n");
                detailInfo.append("  费用金额: ").append(beforeCostDetail.getMoney()).append("\n");
                if (beforeCostDetail.getMainId() != null) {
                    detailInfo.append("  关联订单ID: ").append(beforeCostDetail.getMainId()).append("\n");
                }
            }
            
            if (afterCostDetail != null) {
                detailInfo.append("变化后费用详情:\n");
                detailInfo.append("  费用ID: ").append(afterCostDetail.getId()).append("\n");
                detailInfo.append("  费用名称: ").append(afterCostDetail.getCostClauseName()).append("\n");
                detailInfo.append("  费用金额: ").append(afterCostDetail.getMoney()).append("\n");
                if (afterCostDetail.getMainId() != null) {
                    detailInfo.append("  关联订单ID: ").append(afterCostDetail.getMainId()).append("\n");
                }
            }
            
            costChange.setDetailInfo(detailInfo.toString());
            
            // 使用已初始化的追踪事务ID
            String traceId6 = TRACE_TRANSACTION_ID.get();
            log.debug("从TRACE_TRANSACTION_ID获取的traceId6: {}", traceId6);
            if (traceId6 != null) {
                costChange.setTtid(traceId6);
                log.debug("使用已存在的traceId设置ttid: {}", traceId6);
            } else {
                // 确保链路ID已初始化
                log.debug("TRACE_TRANSACTION_ID为空，调用getTraceTransactionId()初始化");
                getTraceTransactionId();
                traceId6 = TRACE_TRANSACTION_ID.get();
                log.debug("初始化后获取的traceId6: {}", traceId6);
                if (traceId6 != null) {
                    costChange.setTtid(traceId6);
                    log.debug("使用新初始化的traceId设置ttid: {}", traceId6);
                } else {
                    log.warn("TRACE_TRANSACTION_ID 为 null，未能设置 ttid");
                }
            }
            
            costChange.setOperateTime(new Date());
            
            // 设置操作人信息
            setOperatorInfo(costChange);
            
            // 保存记录
            costWeightChangeSourceService.saveOrUpdate(costChange);
            
            // 将当前变化加入追踪链
            addToChangeChain(costChange);
        } catch (Exception e) {
            log.error("记录订单费用变化时发生错误，费用类型: {}", costType, e);
        }
    }
    
    /**
     * 记录订单费用变化源头
     */
    private void recordOrderCostChangeSource(CostWeightChangeSource changeSource, Stock beforeStock) {
        try {
            log.info("记录订单费用变化源头，库存ID: {}", beforeStock.getId());
            
            // 确保始终设置基本信息，特别是stockId
            changeSource.setStockId(beforeStock.getId());
            if (changeSource.getCommodityId() == null) {
                changeSource.setCommodityId(beforeStock.getCommodityId());
            }
            if (changeSource.getCommodityName() == null || changeSource.getCommodityName().isEmpty()) {
                changeSource.setCommodityName(beforeStock.getCommodityName());
            }
            // 设置规格ID和规格名称
            if (changeSource.getSpecsId() == null) {
                changeSource.setSpecsId(beforeStock.getSpecsId());
            }
            if (changeSource.getSpecsName() == null || changeSource.getSpecsName().isEmpty()) {
                changeSource.setSpecsName(beforeStock.getSpecsName());
            }
            // 设置库存批次编码
            if (changeSource.getStockBatchNo() == null || changeSource.getStockBatchNo().isEmpty()) {
                changeSource.setStockBatchNo(beforeStock.getStockBatchNo());
            }
            if (changeSource.getBeforeCostWeight() == null) {
                changeSource.setBeforeCostWeight(beforeStock.getCostWeight());
            }
            if (changeSource.getAfterCostWeight() == null) {
                changeSource.setAfterCostWeight(beforeStock.getCostWeight());
            }
            if (changeSource.getChangeAmount() == null) {
                changeSource.setChangeAmount(BigDecimal.ZERO);
            }
            
            // 记录蔬菜单价和包装单价（保持不变）
            if (changeSource.getBeforeGoodsUnitPrice() == null) {
                changeSource.setBeforeGoodsUnitPrice(beforeStock.getGoodsUnitPrice());
            }
            if (changeSource.getAfterGoodsUnitPrice() == null) {
                changeSource.setAfterGoodsUnitPrice(beforeStock.getGoodsUnitPrice());
            }
            if (changeSource.getGoodsUnitPriceChangeAmount() == null) {
                changeSource.setGoodsUnitPriceChangeAmount(BigDecimal.ZERO);
            }
            if (changeSource.getBeforePackageUnitPrice() == null) {
                changeSource.setBeforePackageUnitPrice(beforeStock.getPackageUnitPrice());
            }
            if (changeSource.getAfterPackageUnitPrice() == null) {
                changeSource.setAfterPackageUnitPrice(beforeStock.getPackageUnitPrice());
            }
            if (changeSource.getPackageUnitPriceChangeAmount() == null) {
                changeSource.setPackageUnitPriceChangeAmount(BigDecimal.ZERO);
            }
            
            // 设置订单费用相关信息
            changeSource.setSourceType(6); // 订单费用影响检查
            changeSource.setRemark("订单费用变化影响检查");
            
            // 添加详细信息，说明可能同时发生订单价格修改和订单费用添加
            StringBuilder detailInfo = new StringBuilder();
            detailInfo.append("订单费用影响检查\n");
            detailInfo.append("注意：订单价格修改和订单费用添加可能同时发生\n");
            detailInfo.append("请检查相关的费用变化记录以获取详细信息\n");
            changeSource.setDetailInfo(detailInfo.toString());
            
            // 使用已初始化的追踪事务ID
            String traceId7 = TRACE_TRANSACTION_ID.get();
            log.debug("从TRACE_TRANSACTION_ID获取的traceId7: {}", traceId7);
            if (traceId7 != null) {
                changeSource.setTtid(traceId7);
                log.debug("使用已存在的traceId设置ttid: {}", traceId7);
            } else {
                // 确保链路ID已初始化
                log.debug("TRACE_TRANSACTION_ID为空，调用getTraceTransactionId()初始化");
                getTraceTransactionId();
                traceId7 = TRACE_TRANSACTION_ID.get();
                log.debug("初始化后获取的traceId7: {}", traceId7);
                if (traceId7 != null) {
                    changeSource.setTtid(traceId7);
                    log.debug("使用新初始化的traceId设置ttid: {}", traceId7);
                } else {
                    log.warn("TRACE_TRANSACTION_ID 为 null，未能设置 ttid");
                }
            }
            
            changeSource.setOperateTime(new Date());
            
            // 设置操作人信息
            setOperatorInfo(changeSource);
            
            // 保存记录
            costWeightChangeSourceService.saveOrUpdate(changeSource);
            
            // 将当前变化加入追踪链
            addToChangeChain(changeSource);
        } catch (Exception e) {
            log.error("记录订单费用变化源头时发生错误，库存ID: {}", beforeStock.getId(), e);
        }
    }
    
    /**
     * 分析订单费用变化源头
     */
    private void analyzeOrderCostChangeSource(CostWeightChangeSource changeSource, ProceedingJoinPoint point, Object[] args, OrderCost orderCost) {
        try {
            log.info("分析订单费用变化源头，订单费用ID: {}", orderCost != null ? orderCost.getCostClauseName() : "unknown");
            
            // 设置基本信息
            if (orderCost != null) {
                changeSource.setSourceType(5); // 订单费用变化
                changeSource.setRemark("订单费用 '" + orderCost.getCostClauseName() + "' 发生变化");
                
                // 如果订单费用有关联的订单ID，设置关联信息
                if (orderCost.getMainId() != null) {
                    changeSource.setSourceOrderId(orderCost.getMainId());
                    // 根据mainId查找订单类型
                    // 这里可以根据业务逻辑进一步完善
                }
                
                // 添加详细的费用信息
                StringBuilder detailInfo = new StringBuilder();
                detailInfo.append("订单费用变化详情:\n");
                detailInfo.append("费用ID: ").append(orderCost.getCostClauseName()).append("\n");
                detailInfo.append("费用名称: ").append(orderCost.getCostClauseName()).append("\n");
                detailInfo.append("费用金额: ").append(orderCost.getMoney()).append("\n");
                if (orderCost.getMainId() != null) {
                    detailInfo.append("关联订单ID: ").append(orderCost.getMainId()).append("\n");
                }
                detailInfo.append("变化时间: ").append(new Date()).append("\n");
                changeSource.setDetailInfo(detailInfo.toString());
            }
            
            // 分析变化源头
            analyzeChangeSource(changeSource, point, args);
            
            // 确保链路ID已设置
            if (changeSource.getTtid() == null) {
                log.debug("changeSource的ttid为空，需要设置");
                String traceId = TRACE_TRANSACTION_ID.get();
                log.debug("从TRACE_TRANSACTION_ID获取的traceId: {}", traceId);
                if (traceId != null) {
                    changeSource.setTtid(traceId);
                    log.debug("使用已存在的traceId设置ttid: {}", traceId);
                } else {
                    // 确保链路ID已初始化
                    log.debug("TRACE_TRANSACTION_ID为空，调用getTraceTransactionId()初始化");
                    getTraceTransactionId();
                    traceId = TRACE_TRANSACTION_ID.get();
                    log.debug("初始化后获取的traceId: {}", traceId);
                    if (traceId != null) {
                        changeSource.setTtid(traceId);
                        log.debug("使用新初始化的traceId设置ttid: {}", traceId);
                    } else {
                        log.warn("TRACE_TRANSACTION_ID 为 null，未能设置 ttid");
                    }
                }
            } else {
                log.debug("changeSource的ttid已存在: {}", changeSource.getTtid());
            }
        } catch (Exception e) {
            log.error("分析订单费用变化源头时发生错误", e);
        }
    }

    /**
     * 将变化加入追踪链
     */
    private void addToChangeChain(CostWeightChangeSource changeSource) {
        try {
            CHANGE_CHAIN_TRACKER.get().put(changeSource.getId(), changeSource);
        } catch (Exception e) {
            log.error("将变化加入追踪链时发生错误", e);
        }
    }
    
    /**
     * 查找追踪链中的根变化
     */
    private CostWeightChangeSource findRootChangeInChain() {
        try {
            return CHANGE_CHAIN_TRACKER.get().values().stream()
                .filter(change -> change.getSourceOrderId() != null && change.getSourceOrderId() > 0)
                .findFirst()
                .orElse(null);
        } catch (Exception e) {
            log.error("查找追踪链中的根变化时发生错误", e);
            return null;
        }
    }
    
    /**
     * 检查是否是由于其他订单修改引起的关联变化
     */
    private void checkRelatedOrderChanges(CostWeightChangeSource changeSource) {
        try {
            // 这里可以添加检查逻辑，检查是否由于其他订单的修改引起了当前库存成本的变化
            // 暂时留空，可根据具体业务需求实现
            log.debug("检查关联订单变化，库存ID: {}", changeSource.getStockId());
        } catch (Exception e) {
            log.error("检查关联订单变化时发生错误", e);
        }
    }

    /**
     * 检查GoodsUnitPrice是否发生变化
     */
    private boolean hasGoodsUnitPriceChanged(Stock beforeStock, Stock afterStock) {
        if (beforeStock.getGoodsUnitPrice() == null && afterStock.getGoodsUnitPrice() == null) {
            log.debug("库存GoodsUnitPrice比较 - 两者都为null，无变化");
            return false;
        }
        if (beforeStock.getGoodsUnitPrice() == null || afterStock.getGoodsUnitPrice() == null) {
            log.debug("库存GoodsUnitPrice比较 - 其中一个为null，有变化，变化前: {}, 变化后: {}",
                    beforeStock.getGoodsUnitPrice(), afterStock.getGoodsUnitPrice());
            return true;
        }
        boolean changed = beforeStock.getGoodsUnitPrice().compareTo(afterStock.getGoodsUnitPrice()) != 0;
        if (changed) {
            log.debug("库存GoodsUnitPrice比较 - 值发生变化，变化前: {}, 变化后: {}",
                    beforeStock.getGoodsUnitPrice(), afterStock.getGoodsUnitPrice());
        } else {
            log.debug("库存GoodsUnitPrice比较 - 值未发生变化，当前值: {}", beforeStock.getGoodsUnitPrice());
        }
        return changed;
    }

    /**
     * 检查PackageUnitPrice是否发生变化
     */
    private boolean hasPackageUnitPriceChanged(Stock beforeStock, Stock afterStock) {
        if (beforeStock.getPackageUnitPrice() == null && afterStock.getPackageUnitPrice() == null) {
            log.debug("库存PackageUnitPrice比较 - 两者都为null，无变化");
            return false;
        }
        if (beforeStock.getPackageUnitPrice() == null || afterStock.getPackageUnitPrice() == null) {
            log.debug("库存PackageUnitPrice比较 - 其中一个为null，有变化，变化前: {}, 变化后: {}",
                    beforeStock.getPackageUnitPrice(), afterStock.getPackageUnitPrice());
            return true;
        }
        boolean changed = beforeStock.getPackageUnitPrice().compareTo(afterStock.getPackageUnitPrice()) != 0;
        if (changed) {
            log.debug("库存PackageUnitPrice比较 - 值发生变化，变化前: {}, 变化后: {}",
                    beforeStock.getPackageUnitPrice(), afterStock.getPackageUnitPrice());
        } else {
            log.debug("库存PackageUnitPrice比较 - 值未发生变化，当前值: {}", beforeStock.getPackageUnitPrice());
        }
        return changed;
    }

}